簡體   English   中英

如何使用Java獲取文本文件的兩行之間的文本

[英]How can I get the text between two lines of a text file using java

如何使用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. 找到的值:在16年7月22日08:07的order \\ POST_ORDER_UpdateTaxAmountCurrInCo.sql:Chathura aBhanakana1
  2. 找到的值:order \\ POST_ORDER_UpdateTaxAmountChathura aBhanakana1AAAAA

在這里檢查輸出

使用拆分方法

示例代碼:

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

在這里檢查輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM