只替换字符串中的一些字符

时间:2014-06-29 22:31:08

标签: java regex

我正在寻找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

这是因为模式应该在单词中完全匹配。但是,是否存在仅替换模式中匹配字符的功能?

1 个答案:

答案 0 :(得分:4)

如何使用character class

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