1

I need to replace all the occurrences of a word in a String when it is between non alpha characters(digits, blankspaces...etc) or at the beginning or the end of the String for a $0. However, my Regex pattern does not seem to work when I use replaceAll.

I have tried several solutions which I found on the web, like Pattern.quote, but the pattern doesn't seem to work. However, it works perfectly on https://regexr.com/

public static final String REPLACE_PATTERN = "(?<=^|[^A-Za-z])(%s)(?=[^A-Za-z]|$)";

String patternToReplace = String.format(REPLACE_PATTERN, "a");

inputString = inputString.replaceAll(Pattern.quote(patternToReplace), "$0");

For example, with the string and the word "a":

a car4is a5car

I expect the output to be:

$0 car4is $05car
Nir Levy
  • 12,750
  • 3
  • 21
  • 38

4 Answers4

0

Pattern.quote() returns regex literal and everything in-between is treated like a text.

You should use Matcher to replace all string occurrences. Besides that, as @Donat pointed out, $0 is treated like a regex variable, so you need to escape it.

inputString = Pattern.compile(patternToReplace).matcher(inputString).replaceAll("\\$0");
Genhis
  • 1,484
  • 3
  • 27
  • 29
0

When you want to replace the matching parts of the string with "$0", you have to write it
"\\$0". This is because $0 has a special meaning: The matching string. So you replace the string by itself.

Donat
  • 4,157
  • 3
  • 11
  • 26
0

You are quoting the wrong thing. You should not quote the pattern. You should quote "a" - the part of the pattern that should be treated literally.

String patternToReplace = String.format(REPLACE_PATTERN, Pattern.quote("a"));

If you are never going to put anything other letters in the second argument of format, then you don't need to quote at all, because letters do not have special meaning in regex.

Additionally, $ has special meaning when used as the replacement, so you need to escape it:

inputString = inputString.replaceAll(patternToReplace, "\\$0");
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Just change from inputString.replaceAll(Pattern.quote(patternToReplace), "$0"); to inputString.replaceAll(patternToReplace, "\\$0");

I have tested with this code :

public static final String REPLACE_PATTERN = "(?<=^|[^A-Za-z])(%s)(?=[^A-Za-z]|$)";
String patternToReplace = String.format(REPLACE_PATTERN, "a");
inputString = inputString.replaceAll(patternToReplace, "\\$0");
System.out.println(inputString);

Output :

$0 car4is $05car

Hope this helps you :)

Anish B.
  • 9,111
  • 3
  • 21
  • 41