2014-11-14 61 views
0

說我編譯正則表達式模式:Java的模式匹配行爲

String myString = "manifest"; 
p = Pattern.compile(myPattern, Pattern.CASE_INSENSITIVE ); 
Matcher m = p.matcher(myString); 
if (m.matches()){ 
    ..... 
} 

當我指定myPattern作爲ni例如,myString沒有得到匹配。但是,當我指定myPattern.*ni.*時,它會得到匹配。

在我的代碼的後面部分,我將要用新模式替換myPattern中定義的任何內容。例如,如果我指定ni作爲要替換的2個字符,則它將只替換ni。如果我指定.*ni.*,那麼整個字符串將被替換爲新的模式。現在我的問題是它不匹配。

有什麼可以解決這個問題? 感謝

+0

照片直接使用.replace? – vks

+0

*你好嗎*'m'? –

回答

3

這一切都取決於它Matcher方法使用:

  • 匹配():當且僅當整個區域的序列匹配此匹配器模式
  • find()方法:如果爲true且僅當,輸入序列的子序列相匹配此匹配器模式

實施例:

String input = "manifest"; 
Matcher m1 = Pattern.compile("ni").matcher(input); 
System.out.println(m1.matches()); // false 
System.out.println(m1.find()); // true 
Matcher m2 = Pattern.compile(".*ni.*").matcher(input); 
System.out.println(m2.matches()); // true 
System.out.println(m2.find()); // false 

此外,發現(),您可以遍歷匹配:

while (m2.find()) { 
    String groupX = m2.group(x); 
} 
4

matches嘗試匹配針對圖案的整個輸入(因爲它在文檔中表示),當然manifest不是ni精確匹配,但是對於.*ni.*精確匹配。但是,例如,如果您使用find,它將在的輸入內搜索某處的模式。還有lookingAt,它會嘗試匹配輸入內「當前」位置的模式。

+0

嗨,謝謝,我用'火柴'。所以我應該使用'find' ...我會試試看。謝謝 – dorothy