在行

时间:2017-03-14 00:30:08

标签: java regex

My String就像这样(一行):

String input = "Details of all persons. Person=details=John Smith-age-22; Person=details=Alice Kohl-age-23; Person=details=Ram Mohan-city-Dallas; Person=details=Michael Jack-city-Boston;"

我想找出使用​​正则表达式匹配所有人的详细信息(基本上是文本从详细信息到分号之前的字符)。我有兴趣找到:

details=John Smith-age-22
details=Alice Kohl-age-23
details=Ram Mohan-city-Dallas
details=Michael Jack-city-Boston

有人能告诉我怎么做吗?对不起,我在网上找不到任何这样的例子。谢谢。

2 个答案:

答案 0 :(得分:0)

您可以尝试使用此代码。

public static void main(String[] args) {
    String input = "Details of all persons. Person=details=John Smith-age-22; Person=details=Alice Kohl-age-23; Person=details=Ram Mohan-city-Dallas; Person=details=Michael Jack-city-Boston;";
    Pattern pattern = Pattern.compile("(?<=Person=).*?(?=;)");
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        String str = matcher.group();
        System.out.println(str);
    }
}

没有断言

public static void main(String[] args) {
    String input = "Details of all persons. Person=details=John Smith-age-22; Person=details=Alice Kohl-age-23; Person=details=Ram Mohan-city-Dallas; Person=details=Michael Jack-city-Boston;";
    Pattern pattern = Pattern.compile("Person=.*?;");
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        String str = matcher.group();
        System.out.println(str.substring(7, str.length()-1));
    }
}

答案 1 :(得分:0)

我怀疑如果您将要查找的字段放入组中,您会发现它最简单,以便您可以提取所需的详细信息。

类似的东西:

Pattern personPattern = Pattern.compile("Person=details=(\\w+)-(age-\\d+|city-\\w+); ");

Matcher matcher = personPattern.match(input);
while (matcher.find()) {
    String name = matcher.group(1);
    String field = matcher.group(2);
    ...
}
相关问题