2013-07-01 63 views
0

我正在寫一個正則表達式來匹配「japan」的每一個出現處,並用「Japan」替換它。爲什麼下面的工作不成功?而「日本」可以在一個句子中的任何地方出現多次。我想替換所有的事件用另一個替換所有出現的單詞

public static void testRegex() 
{ 
    String input = "The nonprofit civic organization shall comply with all other requirements of section 561.422, japan laws, in obtaining the temporary permits authorized by this act."; 
    String regex = "japan"; 
    Pattern p = Pattern.compile(regex); 
    Matcher m = p.matcher(input); 
    System.out.println(input.matches(regex)); 
    System.out.println(input.replaceAll(regex, "Japan")); 

} 
+0

當你運行這個時你會得到什麼輸出? –

+0

什麼在這裏不起作用?你的replaceAll對我來說似乎很好。 –

+0

正則表達式匹配評估爲false。 – Phoenix

回答

7

您不需要這裏的正則表達式,也不需要Pattern和Matcher類。使用簡單String.replace()將正常工作:

input = input.replace("japan", "Japan"); 
+0

我必須使用正則表達式,因爲這是一個外部API,我正在使用 – Phoenix

+1

@Phoenix。它仍然不能說服我使用正則表達式。你用什麼方式使用api? –

+0

它是通過彈簧配置的 – Phoenix

2

replaceAll是否按預期運行。

從您的評論:

正則表達式匹配結果爲false。

此語句評估爲false

System.out.println(input.matches(regex)); 

String#matches相匹配的完整的String。由於String"japan"不是一個正則表達式,你可以做

System.out.println(input.contains(regex)); 
0

input.matches(regex)自錨你的模式與^$。只需用.*即可將您的模式包圍以匹配。

但之後,replaceAll將不再工作。因此,您必須用$1Japan$2替換(.*?)japan(.*?)

相關問題