2016-09-25 39 views
1

我有這樣一句臺詞:正則表達式取兩線

ERROR: file' user\username\file\myfile.mp3' c 
annot be used, because required software is not installed. 
Follow the given instruction below 
instruction one............. 

我希望有一個正則表達式將覆蓋

first two line that means from "ERROR" to "is not installed". 

我用下面

(ERROR\:[^\.]+\.?) 

但只需要

ERROR: file' user\username\file\myfile 

任何形式的幫助將不勝感激,謝謝

+3

您正在使用哪種正則表達式引擎?大多數有一個「多線」模式,其中(例如)'^'將匹配輸入的開始(而不是行的開始)。 – Richard

+0

@Richard實際上我在https://regex101.com/網站上驗證它,我正在windows上爲powershell做 –

+0

輸入不一樣總是......還有其他字符串而不是輸入 –

回答

3

你可以使用這個表達式:

\bERROR:[\s\S]*?\.(?=[\r\n]) 

RegEx Demo

它開始與文字匹配ERROR:匹配和一切,包括換行字符,直到DOT只是一個換行符之前的發現。

+1

偉大.....感謝您的幫助。 –

1

如果我們能夠依靠有是所期望的消息後,一個空行的格式,我們可以用它來捕捉消息本身:

/ERROR\:[\W\w]*?(?=\r?\n\r?\n)/

  • ERROR\:文字文字。
  • [\W\w]*?匹配任何字符零次或多次,但儘可能少次。這意味着它將匹配接下來應該發生的事情。
  • (?=\r?\n\r?\n)如果以下字符組成空行,則匹配。 (但不包括文本作爲比賽本身的一部分。)
+0

你的回答是好的,但我錯誤地把一條新的線,因爲我刪除了新線,它需要所有....你可以請檢查一遍,並幫我一個忙,以便我可以接受它作爲答案。 –

0

通過使用java.util.regex

public static void main(String[] args) { 
     String line = "ERROR: file' user\\username\\file\\myfile.mp3' c\n"+ 
        "annot be used, because required software is not installed.\n\n"+ 
        "Follow the given instruction below\n"+ 
        "instruction one.............\n"; 

     String regex = "^ERROR: [A-Za-z0-9\\.,'\\s\\\\\n]+(?=\\s{2})"; 

     Pattern pattern = Pattern.compile(regex); 
     Matcher matcher = pattern.matcher(line); 
     if(matcher.find()) { 
     System.out.println(line); 
     System.out.println(matcher.group(0)); 
     } 
} 

您將獲得:

ERROR: file' user\username\file\myfile.mp3' c 
annot be used, because required software is not installed. 

Follow the given instruction below 
instruction one............. 

ERROR: file' user\username\file\myfile.mp3' c 
annot be used, because required software is not installed. 

對於regex101.com

^ERROR: [A-Za-z0-9\\.,'\s\\\n]+(?=\s{2}) 

查看結果:https://regex101.com/r/sL8vQ3/1

+0

它不工作,如果你在regex101.com看到它,你會看到 –

+0

我更新了我的答案。希望它有幫助。 –

+0

對不起,它不在regex101.com工作,複製我的行並粘貼到該網站,比使用你的解決方案,希望你會發現不同。 –