Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 仅替换字符串中的某些字符_Java_Regex - Fatal编程技术网

Java 仅替换字符串中的某些字符

Java 仅替换字符串中的某些字符,java,regex,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 patte

我正在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
这是因为模式应该在单词中完全匹配。但是,是否有只替换模式中匹配字符的功能?

使用


如果我必须使用序列所在的变量模式,怎么样?这个(“[”+图案+”)不起作用你使用的是
replaceAll
而不是
replace
?我使用的是replace而不是replaceAll。现在它起作用了。谢谢。另外,我也不太明白为什么我的问题被否定了???我已经正确地表述了这个问题,并提供了尽可能多的细节??可能是因为研究工作不周
x = ex1.replaceAll("[12]", "");