java - 字符串中的换行符检测

java - newline detection in strings

我知道类似的问题已被问过多次,但我看到的答案要么是解决方法,要么根本不正确。

基本问题相当简单:一个方法给我一个从文件中读取的字符串,我需要检查这个字符串是否包含换行符。

现在到了棘手的部分:Wikipedia 目前列出了八种类型的字符或字符组合,根据系统的不同,它们可能表示换行符。所以检查常见的 \n\r,一个我经常阅读的答案,不是要走的路。遍历字符串并将其字符与 System.getProperty("line.separator") 进行比较也可能会失败,因为可能的换行符表示为“\r\n”,这将触发两次比较,尽管它只有一个换行符。

但是,这必须是可能的。我缺少什么选项?

您可以尝试使用正则表达式模式 \r?\n,其中 \r 是可选的。

示例代码:

    String str = "abc\r\nlmn\nxyz";
    Pattern pattern = Pattern.compile("\r?\n");
    Matcher matcher = pattern.matcher(str);
    int count=0;
    while(matcher.find()){
        count++;
    }
    System.out.println(count);    // prints 2

您可以将正则表达式模式 ^(.*)$ 与修饰符 Pattern.MULTILINE 一起使用。检查字符串是否包含任何换行符的方法如下所示:

static boolean containsNewLine(String str) {
    Pattern regex = Pattern.compile("^(.*)$", Pattern.MULTILINE);
    return regex.split(str).length > 0;
}

它将字符串分成 n 个部分,具体取决于换行符的数量。如果字符串包含任何换行符,则 length 将大于 0。

通常 ^$ 将只匹配字符串的开头和结尾,但您可以通过传递 Pattern.MULTILINE 来更改此行为。来自 docs:

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.