2

I'm working on one requirement. I receives input string in below format.

A:82% X 18% Y B:100% X C:82% X 18% Y AB:60% X 20% Y 20% ZZ

String Explanation,

1) String consists of multiple material names like below are the material names present in above mentioned string

        A
        B
        C
        AB

2) Every material is made up of different constituents, For example A is made from 82% of X and 18% of Y. In another input string according to material name the ratio of ingredients can split accordingly. But total is always 100%

3) A string can have multiple material names and one material can be made of n number of ingredients (Total percentage would be 100%)

I want to convert my input string in below format

#A:82% X,18% Y #B:100% X #C:82% X, 18% Y #AB:60% X,20% Y,20% ZZ

I'm able to achieve hash part using regex, code snippet

String inp = "A:82% X 18% Y B:100% X C:82% X 18% Y AB:82% X 18% Y";
String regex = "(\\b[A-Za-z]{1,}\\:\\b)";   
System.out.println(inp.replaceAll(regex, "#$1"));

But am not able to handle or not getting idea for setting up commas in between ingredients of specific material.

Any suggestions please....?

0

2 Answers 2

1

Here's a possible solution leveraging Java 8 streams and regex.

String input = "A:82% X 18% Y B:100% X C:82% X 18% Y AB:60% X 20% Y 20% ZZ";
System.out.println(
        // streaming chunks of input delimited by start of expression
        Stream.of(
            input.split("(?=(^| )\\p{L}+:)")
        )
        // mapping each chunk to replacements
        .map(
            s ->
                // pre-pending # 
                s.replaceAll("(\\p{L}+:)", "#$1")
                // pre-pending comma for multiple value percentages
                .replaceAll("(?= \\d+% \\p{L})",",")
        )
        // collecting by trivial join
        .collect(Collectors.joining())
);

Output

#A:82% X, 18% Y #B:100% X #C:82% X, 18% Y #AB:60% X, 20% Y, 20% ZZ
Sign up to request clarification or add additional context in comments.

Comments

0

You can use negative lookahead:

String inp = "A:82% X 18% Y B:100% X C:82% X 18% Y AB:82% X 18% Y";
String regex = "(\\b[A-Za-z]{1,}\\:\\b)";
String regexToPlaceComa = "(\\d{1,3}% [a-zA-Z]+) (?!#)";
inp = inp.replaceAll(regex, "#$1");
inp = inp.replaceAll(regexToPlaceComa, "$1,");
System.out.println(inp);

Also in your regex: "\\" character escape before ":" is redundant, and "{1,}" you can replace with "+" like below:

regex = "(\\b[A-Za-z]+:\\b)";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.