Search code examples
javaregexreplaceall

Java replaceAll regex error


I want to transforme all "*" into ".*" excepte "\*"

String regex01 = "\\*toto".replaceAll("[^\\\\]\\*", ".*");
assertTrue("*toto".matches(regex01));// True

String regex02 = "toto*".replaceAll("[^\\\\]\\*", ".*");
assertTrue("tototo".matches(regex02));// True

String regex03 = "*toto".replaceAll("[^\\\\]\\*", ".*");
assertTrue("tototo".matches(regex03));// Error

If the "*" is the first character a error occure : java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0

What is the correct regex ?


Solution

  • You need to use negative lookbehind here:

    String regex01 = input.replaceFirst("(?<!\\\\)\\*", ".*");
    

    (?<!\\\\) is a negative lookbehind that means match * if it is not preceded by a backslash.

    Examples:

    regex01 = "\\*toto".replaceAll("(?<!\\\\)\\*", ".*");
    //=> \*toto
    
    regex01 = "*toto".replaceAll("(?<!\\\\)\\*", ".*");
    //=> .*toto