我需要在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"));
...这仍然会为第三个a;b委派空输入到ByteArrayInputStream。
Hoe,我可以检查fileScanner.next()的第一行是否为空行,然后执行nextLine()语句和后续的继续语句吗?
发布于 2012-11-05 13:04:41
使用regex模式
(?m)^(?:.+(?:\\r?\\n|\\Z)){2,}它匹配两个或多个非空行,或其他两个或多个(?:...){2,}行,这些行包含一个或多个字符.+,后面跟着字符串\\Z的新行\\r?\\n或(?:...|...)结束。
多行修饰符(?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);
}见这个演示。
https://stackoverflow.com/questions/13232689
复制相似问题