Java正则表达式。奇怪的行为

时间:2013-04-11 12:00:46

标签: java regex

有人可以帮助正则表达吗?这段代码很好用。

public static void main(String[] args) {

    String s = "with name=successfully already exist\n";

    Pattern p = Pattern.compile(".+name=.*successfully.+", Pattern.DOTALL);
    java.util.regex.Matcher m = p.matcher(s);

    if (m.matches()) {
        System.out.println("match");
    } else {
        System.out.println("not match");
    }

}

但是这段代码返回“不匹配”。为什么呢?

public static void main(String[] args) {

    String s = "with name=successfully already exist\n";

    if (s.matches(".+name=.*successfully.+")) {
        System.out.println("match");
    } else {
        System.out.println("not match");
    }

}

2 个答案:

答案 0 :(得分:5)

两者之间的唯一区别是第一个例子中的DOTALL标志。

如果没有该标志,则字符串末尾的\n将与最后一个模式(.+)不匹配。

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#DOTALL

  

在dotall模式下,表达式。匹配任何字符,包括行终止符。默认情况下,此表达式与行终止符不匹配。

请注意matches尝试匹配整个字符串(在您的情况下包括尾随换行符),而不仅仅是尝试查找子字符串(这在Java中与许多其他语言不同)。

答案 1 :(得分:4)

使用compile()时提供的Pattern.DOTALL参数使其成为'。'匹配'行尾终结符'。您需要提供内联标记以使matches()执行相同操作。请尝试以下方法:

s.matches("(?s).+name=.*successfully(?s).+")

干杯。