为什么带换行符的字符串与Java中的正则表达式不匹配?

时间:2014-09-17 07:22:39

标签: java regex string newline

我有一个字符串string,其中包含换行符(\n)。当我尝试将它与正则表达式pattern匹配时,它返回false,尽管应该匹配。

package com.stackoverflow;

public class ExgExTest {

    public static void main(String[] args) {
        String pattern = ".*[0-9]{2}[A-Z]{2}.*";
        String string  = "123ABC\nDEF";

        if (string.matches(pattern)) {
            System.out.println("Matches.");
        } else {
            System.out.println("Does not match.");
        }

    } // END: main()

} // END: class

如何将多行字符串与正则表达式匹配?

2 个答案:

答案 0 :(得分:3)

  

如何将多行字符串与正则表达式匹配?

您需要使用DOTALLs)标记:

String pattern = "(?s).*[0-9]{2}[A-Z]{2}.*";

注意(?s)DOT也会匹配新行。

答案 1 :(得分:0)

您应该使用Pattern.quote(pattern)来转义模式中的所有特殊字符。

Documentation