2016-04-14 65 views
0

後,我已經得到了以下文字:Unbekannter Fehler: while trying to invoke the method test() of a null object loaded from local variable 'libInfo'正則表達式與前面的任何字符和給定的字符串

Matcher matcher = null; 
Pattern pattern = null; 
try 
{ 
    pattern = Pattern.compile(".*" + "Unbekannter Fehler: while trying to invoke the method test() of a null object loaded from local variable 'libInfo'" + ".*", Pattern.CASE_INSENSITIVE & Pattern.DOTALL); 
    matcher = pattern.matcher("Unbekannter Fehler: while trying to invoke the method test() of a null object loaded from local variable 'libInfo'"); 

    if (matcher.matches()) 
     System.out.println("Same!"); 
} 

如果我運行上面的代碼,它返回false,但是爲什麼呢?我只是想檢查一下,如果文本是由正則表達式(No String.contains(...))包含的。如果我正確地閱讀它,我必須在正則表達式的開頭和結尾使用.*以確保它不會在檢查字符串之前或之後發生什麼。

+0

保持從您的模式中刪除字符,直到它匹配,然後你會知道什麼字符造成它不匹配。 –

回答

3

確保您的所有角色都先被正確轉義。嘗試使用Pattern#quote

String test = "Unbekannter Fehler: while trying to invoke the method test() of a null object loaded from local variable 'libInfo'"; 

Pattern pattern = Pattern.compile(".*" + Pattern.quote(test) + ".*", Pattern.CASE_INSENSITIVE & Pattern.DOTALL); 
Matcher matcher = pattern.matcher(test); 

if (matcher.matches()) { 
    System.out.println("Same!"); 
} 
1

您必須引用模式中的括號。

pattern = Pattern.compile("Unbekannter Fehler: while trying to invoke the method test\\(\\) of a null object loaded from local variable 'libInfo'", Pattern.CASE_INSENSITIVE & Pattern.DOTALL); 

你不應該在開始時需要.*,也不要結束。

Regards