如何在正则表达式中使用\ n?

时间:2013-10-12 04:09:30

标签: java regex

初始字符串是

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 ???

1 个答案:

答案 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);