Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the below pattern from a string?

Tags:

java

string

regex

I have a string which looks like below.

{(firstName1,lastName1,College1,{(24,25)},{(Street,23)},City1,Country1)}

I need to extract the details/values from the above and add them to a list. By details I mean:

 ["firstName1","lastName1","College1","24","25","Street","23","City1", "country1"]

How can I achieve the above? I tried the below method but not sure how to get all curly braces and brackets into the pattern.

private static String flattenPigBag(String pigdata) {
    String s = "";
    Pattern p = Pattern.compile("\\{(.*)}");
    Matcher m = p.matcher(pigdata);
    while (m.find()) {
        s = m.group(1);
        System.out.println("answer : " + s);
    }
    return s;
}
like image 288
AnOldSoul Avatar asked Jul 23 '26 02:07

AnOldSoul


2 Answers

Try this:

String[] parts = str.replaceAll("}|\\{", "").split(",");
like image 174
Bohemian Avatar answered Jul 24 '26 15:07

Bohemian


Are you forced to use a pattern? If not, feel free to use this.

private static List<String> flattenPigBag(String s) {
    return Arrays.asList(s.replaceAll("[(){}]", "").split(","));
}

Output:

[firstName1, lastName1, College1, 24, 25, Street, 23, City1, Country1]
like image 22
Jacob G. Avatar answered Jul 24 '26 16:07

Jacob G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!