我正在尝试使用 RegEx 解释多行字符串,但发现如果字符串包含换行符,匹配将失败。我没有使用 MULTILINE
模式,因为我没有使用 anchor 。根据 API 文档:
In multiline mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the input sequence. By default these expressions only match at the beginning and the end of the entire input sequence.
简而言之:它清楚地表明这个标志只改变 anchor 的工作方式,并没有说“当你的字符串包含换行符时你绝对应该使用它”。
public static void main(String[] args) {
Pattern p = Pattern.compile(".*");
Matcher m1 = p.matcher("Hello");
System.out.println("m1: " + m1.matches()); // true
Matcher m2 = p.matcher("Hello\r\n");
System.out.println("m2: " + m2.matches()); // false
}
这真的是一个错误,还是我只是错过了一些文档?或者 JAVA 在我的模式失败的地方使用 RegEx 方言?我正在使用 jdk1.6.0_21
。
最佳答案
来自Pattern docs :
The regular expression
.
matches any character except a line terminator unless the DOTALL flag is specified.
因此,如果您希望 m2.matches()
为真,则需要指定 DOTALL
标志。
关于Java RegEx 和换行符 - 错误或预期行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5528986/