3

I have a configuration file in which I am replacing some placeholder(variables) with their actual value after parsing an excel file. I am using the below pattern:

word = word.startsWith("$") ? word.substring(1) : word;
                  return input.replaceAll(Pattern.quote("$"+word),
                   Matcher.quoteReplacement(prefix));

The above is replacing all the sub-strings as well as is case sensitive. For example if I have the below 2 variables: $Building $Building1 , both are different variables. But the above replaces the value of Building in both cases and appends it with "1" in the second case. Could you guys please help me change the pattern. I have tried case_insensitive option but that did not work fine.

0

1 Answer 1

4

You can use a word boundary \b:

return input.replaceAll(Pattern.quote("$"+word) + "\\b",
                                      Matcher.quoteReplacement(prefix));
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! But i am thinking it looks for a boundary in the above case. In my case there could be a space between two variables or not
Also how do I make it case insensitive?
@sahana use (?i) as prefix.
I have tried (?i) in front of word like----------- return input.replaceAll(Pattern.quote("$"+(?i)word) + "\\b", Matcher.quoteReplacement(prefix));-- it does not work. Could you correct me
put (?i) before Pattern: "(?i)" + Pattern...

Your Answer

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.