Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.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 String.replaceAll不替换并发重复序列_Java_Regex_String_Replaceall - Fatal编程技术网

Java String.replaceAll不替换并发重复序列

Java String.replaceAll不替换并发重复序列,java,regex,string,replaceall,Java,Regex,String,Replaceall,我正在尝试使用String.replaceAll从字符串中删除一些空格。但是,当多个regex模式的并发实例出现在字符串中时,仅每隔第二个实例被替换一次 非常简单的例子: String theString = "foo x x x x x bar"; String trimmed = theString.replaceAll("x\\s*x", "xx"); System.out.println(theString); System.out.println(tri

我正在尝试使用String.replaceAll从字符串中删除一些空格。但是,当多个regex模式的并发实例出现在字符串中时,仅每隔第二个实例被替换一次

非常简单的例子:

String theString = "foo x x x x x bar";        
String trimmed = theString.replaceAll("x\\s*x", "xx");        
System.out.println(theString);
System.out.println(trimmed);
我想看到的是:

foo x x x x x bar
foo xxxxx bar
我看到:

foo x x x x x bar
foo xx xx x bar

似乎RePATALL不认为替换文本是被替换的候选,而是愉快地向前跳跃。


是否有一个简单的解决方法?

问题是您在空格后匹配
x
;因此,在第一场比赛后,您将:

foo x x x x x bar
       ^
       |---- HERE
你不想吞下它;您必须使用前瞻:

.replaceAll("x\\s+(?=x)", "x");
您甚至可以同时使用“向前看”和“向后看”:

.replaceAll("(?<=x)\\s+(?=x)", "");

>代码> >(RealPosith.RePASTALL)(看起来)RePAREL不考虑替换文本作为替换自身的候选,而是愉快地向前跳跃。正确,对于任何字符串替换方法来说,这都是非常不寻常的行为。非常好,正是我想要的,并且解释得很清楚。非常感谢。如果适合您,请不要忘记接受答案;)
theString.replaceAll("(?<=x)\\s+(?=x)", "");