试一下递归:
public static string RecReplce(string s)
{
string res = Regex.Replace(s, ",a,", ",,");
if (res == s) return res;
else return RecReplce(res);
}
好吧,自己解决一下。。两次replace就可以了。
String.replaceAll(",a,",",,").replaceAll(",a,",",,");
String.replaceAll(",a,",",,")
abc,aa,a,a,a,a
abc,aa,,a,,a
程序很正常,只是你理解错了
String.replaceAll(",a",",")
abc,aa,a,a,a,a
abc,aa,,,,a
后面的程序你没跑过的吧?会匹配到前面的两个aa或者是后面的那个 ,a。我知道replaceAll(",a,",",,")肯定会出来abc,aa,,a,,a的结果,我只是来寻找解决办法的
@BiceG: 我倒是为跑过,确实会匹配到前面那个,我没注意!
String.replaceAll("a,",",")
abc,aa,a,a,a,a
abc,aa,,,,a
public class Test { public static void main(String[] args) { System.out.println(replace2("abc,aa,a,a,a,a,")); } private static String replace2(String strNew) { String str = strNew.replace(",a,", ",,"); if (str.contains(",a,")) { str = replace2(str); } return str; } }
你用正则表达式“,a{1},”去匹配一次,匹配成功的替换为“,,”
将返回的结果再用上述正则表达式进行匹配,匹配成功后按照上述再进行替换,直到没有匹配项为止。
正好是你要的结果“abc,aa,,,,a”