[英]String.replaceAll() issue
I want to replace all exact matching of 我要替换的所有完全匹配
fm.get('Order#
in a lengthy String with value 在带有值的冗长字符串中
fm.get('Order__'
i used syntax like : 我使用了像这样的语法:
String calcStr = "return fm.get('Order#');";
String fname = "Order#";
String validfName = "Order__";
String modifiedCalc1 = calcStr.replaceAll("fm.get('"+fname+"\\b", "fm.get('"+validfName);
System.out.println(modifiedCalc1);
but i am getting pattern error. 但我收到模式错误。
Exception in thread "main" java.util.regex.PatternSyntaxException:
Unclosed group near index 18
\bfm.get('Order#\b
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.accept(Unknown Source)
You need to escape the opening parenthesis and the point. 您需要转义开头的括号和要点。
Remove also the \\b
at the end for this specific case. 在这种情况下,也请删除最后的
\\b
。
String modifiedCalc1 = calcStr.replaceAll("fm\\.get\\('"+fname, "fm.get('"+validfName);
If you want to replace a literal string using an API that expects a regular expression, you can use Pattern.quote
(for the pattern side) and Matcher.quoteReplacement
(for the substitution side): 如果要使用需要正则表达式的API替换文字字符串,则可以使用
Pattern.quote
(用于模式端)和Matcher.quoteReplacement
(用于替代端):
calcStr.replaceAll(Pattern.quote("fm.get('Order#"),
Matcher.quoteReplacement("fm.get('Order__"));
It seems no regexp features are really needed in this case. 在这种情况下,似乎确实不需要正则表达式功能。
So plain string replacement can be used that is much more efficient: 因此,可以使用纯字符串替换来提高效率:
String modifiedCalc1 = calcStr.replace("fm.get('"+fname, "fm.get('"+validfName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.