2015-04-07 94 views
1

我有以下錯誤消息正則表達式來匹配特定的單詞和忽略特定文本

列表
def errorMessages = ["Line : 1 Invoice does not foot Reported" 
        "Line : 2 Could not parse INVOICE_DATE value" 
        "Line 3 : Could not parse ADJUSTMENT_AMOUNT value" 
        "Line 4 : MATH ERROR" 
        "cl_id is a required field" 
        "File Error : The file does not contain delimiters" 
        "lf_name is a required field"] 

想創建哪個犯規匹配regex "^Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.+"一個新的列表,但有Invoice does not foot Reported

我想要的文字新名單應該像下面

def headErrors= ["Line : 1 Invoice does not foot Reported" 
       "cl_id is a required field" 
       "File Error : The file does not contain delimiters" 
       "lf_name is a required field"] 

這是我做的,現在

regex = "^Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.+" 
errorMessages.each{ 
    if(it.contains('Invoice does not foot Reported')) 
     headErrors.add(it) 
    else if(!it.matches(regex) 
     headErrors.add(it) 
} 

有沒有一種方法可以完成只是使用正則表達式而不是如果其他?

回答

2
  1. 首先匹配消息部分中包含文本Invoice does not foot Reported的行。

  2. 然後在開始時使用負向前視斷言,如果它開頭的字符與實際匹配模式的字符不匹配。

正則表達式:

"^Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.*?Invoice does not foot Reported.*|^(?!Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.*).+" 

DEMO

+0

手動測試上'regex101.com'但是當我在我的代碼編譯器使用它給下面的錯誤時,它看起來不錯'非法串身體角色美元符號後;解決方案:或者轉義文字美元符號「\ $ 5」或將括號表達式「$ {5}」' – RanPaul

+0

刪除'$'符號並重試。 –

+0

感謝您的回答。我很感激。你還可以幫助我與這個http://stackoverflow.com/questions/29570648/java-8-find-and-replace-matching-strings – RanPaul

相關問題