0

初始字符串是

System.out.println(myString)

看起来像这样

Name: Sacha
Last name: Sidor
.............
Name: Masha
........

我试图捕捉第二个名字,即玛莎

            Pattern pattern = Pattern.compile("(?:Name:.*?){2}\\n");
            Matcher matcher = pattern.matcher(myString);
            String secondName = "";
            while (matcher.find()) {
            secondName = matcher.group();
              }
            System.out.println(secondName); // prints nothing ???
4

1 回答 1

3

使用Pattern.DOTALL标志.匹配所有字符,包括换行符。没有DOTALL标志,.不匹配换行符。

Pattern pattern = Pattern.compile("(?:Name:.*?)(?:Name: )([^\\n]+)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(myString);
String secondName = "";
if (matcher.find())
    secondName = matcher.group(1);
System.out.println(secondName);
于 2013-10-12T04:19:48.087 回答