[英]How to replace a string in java if replacement string contains special(some regex) character
我正在尝试替换Java中的字符串,其中我的替换字符串包含的特殊字符如下所示。
String s1 = char(1)+"abc"+char(1);
String s2 = "!@#$%^&*()-_`~";
String s3 = s.replaceAll(s1, s2);
上面写的代码抛出java.lang.IllegalArgumentException:非法的组引用
您应该使用正则替换,而不是需要正则表达式的replaceAll
。
用指定的文字替换序列替换此字符串中与文字目标序列匹配的每个子字符串。
样本( http://ideone.com/HbV9eO )
String s= "\u0001abc\u0001more\u0001abc\u0001";
String s1 = "\u0001abc\u0001";
String s2 = "!@#$%^&*()-_`~";
String s3 = s.replace(s1, s2);
System.out.println("new string = " + s3);
Alexei Levenkov的答案中建议的String.replace(CharSequence, CharSequence)
是您要用字面意义上的另一个字符串替换字符串的方法。
为了完整起见,如果要使用replaceAll进行文字字符串替换,则需要同时引用模式字符串和替换字符串,以便对它们进行文字处理(即没有任何特殊含义)。
inputString.replaceAll(Pattern.quote(pattern), Matcher.quoteReplacement(replacement));
Pattern.quote(String)
创建一个从字面上匹配指定字符串的模式。
Matcher.quoteReplacement(String)
为指定的字符串创建一个文字替换字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.