Java 查找一行中所有出现的正则表达式模式

Java 查找一行中所有出现的正则表达式模式,java,regex,Java,Regex,我的字符串如下(一行): 我想使用正则表达式找出匹配所有人员及其详细信息的方法(基本上是从详细信息到分号之前的字符的文本)。我有兴趣发现: details=John Smith-age-22 details=Alice Kohl-age-23 details=Ram Mohan-city-Dallas details=Michael Jack-city-Boston 有人能告诉我怎么做吗?对不起,我在网上找不到这样的例子。谢谢 您可以尝试此代码 public static void main(

我的字符串如下(一行):

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

details=John Smith-age-22
details=Alice Kohl-age-23
details=Ram Mohan-city-Dallas
details=Michael Jack-city-Boston
有人能告诉我怎么做吗?对不起,我在网上找不到这样的例子。谢谢

您可以尝试此代码

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

我想,如果您将要查找的字段分组,以便提取所需的详细信息,您会发现这是最简单的

比如:

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

谢谢你的及时回复,这很有帮助!然而,我以前没有意识到向前看/向后看。虽然我现在看了医生,但我想知道是否还有其他方法(除了前瞻等)?你能解释一下为什么我们需要模式中的第二个“?”字符吗?这有什么帮助?在
*?
中,
不情愿量词的关键词。请阅读“不情愿的量词”的帮助文档。如果没有
,结果将是
details=John Smith-age-22;人员=详细信息=Alice Kohl-age-23;人员=详细信息=达拉斯拉姆莫汉市;Person=details=Michael Jack city Boston
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));
    }
}
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);
    ...
}