Java,正则表达式HASNEXT以空行,多平台支持开始



我需要在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

我需要处理包含下面数据块的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"));
...

这仍然会委派 third a;b bytearrayInputStream中的空输入。

HOE可以检查fileScanner.next()的第一行是否是空行,然后执行NextLine()语句和以下一个继续语句?

使用Regex模式

(?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);
}

请参阅此Demo

最新更新