java - 如何使用java获取文本文件两行之间的文本

标签 java regex

如何使用 Java 获取文本文件两行之间的文本? 我尝试这样做,但它不起作用:

String input = "!!!Error deploying file order\\POST_ORDER_UpdateTaxAmountCurrInCo.sql at 22-JUL-16 08:07:Chathura aBhanakana1!!!Error deploying file order\\POST_ORDER_";
Pattern p = Pattern.compile("(?<=\\b!!!Error deploying file\\b).*?(?=\\b!!!Error deploying file\\b)");
Matcher m = p.matcher(input);
List<String> matches = new ArrayList<String>();
while (m.find()) {
    System.out.println("A " + m.group());
}

最佳答案

更新答案

使用正则表达式

String pattern = "([\\s\\S]*?)(!!!Error deploying file)";

上述模式的解释。

  1. *? - 匹配单个字符零次到无限次
  2. \s - 匹配任何空白字符
  3. \S - 匹配任何非空白字符

示例代码:

String line = "!!!Error deploying file order\\POST_ORDER_UpdateTaxAmountCurrInCo.sql at 22-JUL-16 08:07:Chathura aBhanakana1!!!Error deploying file order\\POST_ORDER_UpdateTaxAmountChathura aBhanakana1AAAAA !!!Error deploying file order\\POST";

String pattern = "([\\s\\S]*?)(!!!Error deploying file)";

// Create a Pattern object
Pattern r = Pattern.compile(pattern);

// Now create matcher object.
Matcher m = r.matcher(line);
while (m.find( )) {
  String str = m.group(1);
  if(str != null && !str.isEmpty()){
     System.out.println("Found value: " + str );
   }
} 

输出

  1. 发现值:order\POST_ORDER_UpdateTaxAmountCurrInCo.sql,位于 2016 年 7 月 22 日 08:07:Chathura aBhanakana1
  2. 发现值: 订单\POST_ORDER_UpdateTaxAmountChathura aBhanakana1AAAAA

Check output here

使用分割方法

示例代码:

String line = "!!!Error deploying file order\\POST_ORDER_UpdateTaxAmountCurrInCo.sql at 22-JUL-16 08:07:Chathura aBhanakana1!!!Error deploying file order\\POST_ORDER_UpdateTaxAmountChathura aBhanakana1AAAAA !!!Error deploying file order\\POST";

for (String retval: line.split("!!!Error deploying file")){
       System.out.println(retval);
 }

输出:

1 ) order\POST_ORDER_UpdateTaxAmountCurrInCo.sql at 22-JUL-16 08:07:Chathura aBhanakana1
2) order\POST_ORDER_UpdateTaxAmountChathura aBhanakana1AAAAA
3) order\POST

Check output here

关于java - 如何使用java获取文本文件两行之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38584845/

相关文章:

Java "partial"覆盖

java - 转义 Java RegEx 元字符

java - 在jdb中调试时 "bci"是什么?

java - "Couldn' t 查找具有权限 com.google.firebase.database.provider 的提供商的元数据”

java - 将字母排成一行

java - 如何对 999-999-9999 等电话号码使用正则表达式 validator

c# - 用于从字符串中删除 HTML 的 .Net 函数?

regex - 如果 URI 包含单词,则在 Apache .htaccess 中设置 header

PHP preg_match 斜杠之间的所有内容

java - 文件类无法使用绝对路径访问文件