我有一个正则表达式"[\ r \n\f] +"来查找字符串中包含的行数.我的代码是这样的:
pattern = Pattern.compile("[\\r\\n\\f]+")
String[] lines = pattern.split(texts);
Run Code Online (Sandbox Code Playgroud)
在我的单元测试中,我有这样的示例字符串:
"\t\t\t \r\n \n"
"\r\n"
Run Code Online (Sandbox Code Playgroud)
解析第一个字符串的结果是2,但是当它解析第二个字符串时它变为0.
我认为第二个字符串包含1行,尽管该行是"空白"(假设我正在编辑一个以文本编辑器中的"\ r \n"开头的文件,插入符号是否应放在第二行?).我的正则表达式是不正确的解析行?或者我在这里遗失了什么?
编辑:
我想我会让问题更加明显:
为什么
// notice the trailing space in the string
"\r\n ".split("\r\n").length == 2 // results in 2 strings {"", " "}. So this block of text has two lines.
Run Code Online (Sandbox Code Playgroud)
但
// notice there's no trailing space in the string
"\r\n".split("\r\n").length == 0 // results in an empty array. Why "" (empty string) is not in the result and …Run Code Online (Sandbox Code Playgroud)