Search code examples
javaregexstringreplaceall

Regular expression for String.replaceAll


I need a regular expression that can be used with replaceAll method of String class to replace all instance of * with .* except for one that has trailing \

i.e. conversion would be

[any character]*[any character] => [any character].*[any character]
* => .*
\* => \* (i.e. no conversion.)

Can someone please help me?


Solution

  • Use lookbehind.

    String resultString = subjectString.replaceAll("(?<!\\\\)\\*", ".*");
    

    Explanation :

    "(?<!" +     // Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind)
       "\\\\" +       // Match the character “\” literally
    ")" +
    "\\*"         // Match the character “*” literally