如何从字符串中提取以下模式?

How to extract the below pattern from a string?

我有一个如下所示的字符串。

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

我需要从上面提取 details/values 并将它们添加到列表中。我的意思是详细信息:

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

如何实现以上目标?我尝试了以下方法,但不确定如何将所有花括号和方括号放入模式中。

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;
}

试试这个:

String[] parts = str.replaceAll("}|\{", "").split(",");

您是否被迫使用一种模式?如果没有,请随意使用它。

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

输出:

[firstName1, lastName1, College1, 24, 25, Street, 23, City1, Country1]

我假设您需要提取各个字段以进行进一步处理。所以这就是我要做的。在我的测试程序中,我只是打印出字段,但我想在您的程序中,您可以获取这些字段值并以某种方式使用它们(例如,将它们应用于 Java 对象的某些设置器)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatchingWithNamedCaptureGroup {

    public static void main(String[] args) {
        String regex = "\{(\("
                + "(?<firstName>[^,]*)"
                + ",(?<lastName>[^,]*)"
                + ",(?<college>[^,]*)"
                + ",\{\("
                + "(?<num1>\d*)"
                + ",(?<num2>\d*)\)\}"
                + ",\{\((?<street>[^,]*)"
                + ",(?<streetNum>\d*)\)\}"
                + ",(?<city>[^,]*)"
                + ",(?<country>[^,]*)"
                + "\))\}";
        String input
        = "{(firstName1,lastName1,College1,{(24,25)},{(Street,23)},City1,Country1)}";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        if (m.find()) {
            String firstName    = m.group("firstName");
            String lastName     = m.group("lastName");
            String college      = m.group("college");
            String num1         = m.group("num1");
            String num2         = m.group("num2");
            String street       = m.group("street");
            String streetNum    = m.group("streetNum");
            String city         = m.group("city");
            String country      = m.group("country");
            System.out.println(firstName
                                + "," + lastName
                                + "," + college
                                + "," + num1
                                + "," + num2
                                + "," + street
                                + "," + streetNum
                                + "," + city
                                + "," + country
                                );
        } else {
            System.err.println("Does not match!");
        }

    }

}

这个程序的输出是这样的:

firstName1,lastName1,College1,24,25,Street,23,City1,Country1