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)
Denys Séguret
384k90 gold badges813 silver badges780 bronze badges
asked Sep 27, 2012 at 14:37
srini
3833 gold badges7 silver badges17 bronze badges
3 Answers 3
You need to escape the opening parenthesis and the point.
Remove also the \b at the end for this specific case.
String modifiedCalc1 = calcStr.replaceAll("fm\\.get\\('"+fname, "fm.get('"+validfName);
answered Sep 27, 2012 at 14:38
Denys Séguret
384k90 gold badges813 silver badges780 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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):
calcStr.replaceAll(Pattern.quote("fm.get('Order#"),
Matcher.quoteReplacement("fm.get('Order__"));
answered Sep 27, 2012 at 14:50
Ian Roberts
123k17 gold badges177 silver badges191 bronze badges
Comments
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);
answered Sep 27, 2012 at 15:09
Vadzim
26.4k14 gold badges153 silver badges160 bronze badges
Comments
lang-java