2014-06-29 98 views
-2

我正在尋找一種Java方式來替換沒有循環的序列中的匹配字符。只替換字符串中的某些字符

String x = "" 
    String pattern = "12" 
    String ex1 = "1254" 
    x = ex1.replace(pattern, ""); 
    System.out.print(x) 
    Output: 
    54 
    In this case 1254 a match is found: 12 

然而,

String x = "" 
    String pattern = "12" 
    String ex1 = "154" 
    x = ex1.replace(pattern, ""); 
    System.out.print(x) 
    Output: 
    154 
    In this case no replacement takes place. 
    The desired output in this case would be: 

    54 

    because only 1 is found from the pattern 

這是因爲圖案應在字完全匹配。然而,是否有一個函數只能從模式中匹配的字符被替換?

回答

4

如何使用character class

x = ex1.replaceAll("[12]", ""); 
+0

怎麼樣,如果我不得不使用其中的序列舉行的變化圖案?這個(「[」+ pattern +「]」不起作用 – user3758223

+0

您是否使用'replaceAll'而不是'replace'? – Reimeus

+0

我正在使用replace而不是replaceAll。現在可以使用了,謝謝。很明白爲什麼我的問題被否定???我已經正確地提出了這個問題,並提供了儘可能多的細節? – user3758223