Java RegEx 和换行符 - 错误或预期行为?

标签 java regex

我正在尝试使用 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/

相关文章:

java - 使用外部 jar 和多个 args 从 python 执行 java 类

Java 正则表达式不匹配德语 "Umlaut"或下划线

C# 正则表达式 for/"在字符串末尾

c# - 使用regex c#获取字符之间的字符串

java - 将 List<BufferedImage> 转换为图像

java - 客户端在 websocket 中一段时间​​后自动断开连接

java - AsyncTask 不会在第一次尝试时调用 OnCancel()

regex - 重复单词的正则表达式

ruby - 如何读取一个文件的内容,然后将内容拆分成几个文件?

java - 这个用于替换转义字符的 Java 正则表达式如何工作?