我有一个包含换行符 (\n
) 的字符串string
。当我尝试将其与正则表达式 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
如何将多行字符串与正则表达式匹配?
最佳答案
How can I match multiline strings with a regular expression?
为此,您需要使用 DOTALL
(s
) 标志:
String pattern = "(?s).*[0-9]{2}[A-Z]{2}.*";
记下(?s)
,这将使DOT
也匹配新行。
关于java - 为什么带有换行符的字符串与Java中的正则表达式不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25884647/