2

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
0

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.