初始字符串是
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 ???
答案 0 :(得分: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);