Search code examples
javaregexreplaceall

ReplaceAll when it is not alpha characters


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

Solution

  • 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 :)