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

时间:2016-12-15 04:11:44

标签: java regex string pattern-matching matcher

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

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

我需要从上面提取细节/值并将它们添加到列表中。我的意思是:

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

3 个答案:

答案 0 :(得分:6)

试试这个:

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

答案 1 :(得分:3)

你被迫使用一种模式吗?如果没有,请随意使用。

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

输出:

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

答案 2 :(得分:2)

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

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