我需要在 Unix 和 Windows 上处理以下文件:
a;b
c;d;e;f;g
c;d;e;f;g
c;d;e;f;g
a;b
c;d;e;f;g
c;d;e;f;g
c;d;e;f;g
a;b
a;b
c;d;e;f;g
c;d;e;f;g
c;d;e;f;g
我需要处理下面包含数据 block 的a;b
。
例如第三个 a;b
不应被处理。
目前,我正在使用 Java 扫描器在文件中使用以下正则表达式来分隔此类文本:
Scanner fileScanner = new Scanner(file);
try{
fileScanner.useDelimiter(Pattern.compile("^$", Pattern.MULTILINE));
while(fileScanner.hasNext()){
String line;
while ((line = fileScanner.nextLine()).isEmpty());
InputStream is = new ByteArrayInputStream(fileScanner.next().getBytes("UTF-8"));
...
这仍然会将第三个 a;b
的空输入委托(delegate)到 ByteArrayInputStream 中。
我可以检查一下 fileScanner.next()
的第一行是否为空行,然后执行 nextLine() 语句和后面的 continue 语句吗?
最佳答案
使用正则表达式模式
(?m)^(?:.+(?:\\r?\\n|\\Z)){2,}
匹配两个或多个非空行,或者两个或多个 (?:...){2,}
行,其中包含一个或多个字符 .+
后跟换行符 \\r?\\n
或 (?:...|...)
字符串末尾 \\Z
。
多行修饰符 (?m)
表示 ^
匹配每行的开头,而不仅仅是字符串的开头。
演示:
String str = "...";
Pattern p = Pattern.compile("(?m)^(?:.+(?:\\r?\\n|\\Z)){2,}");
Matcher m = p.matcher(str);
while (m.find()) {
String match = m.group();
System.out.println(match);
}
参见this demo 。
关于Java、正则表达式HasNext以空行开头,多平台支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13232689/