0

I've got my own indexOf function

private static int indexOf(String target, String pattern){

    Pattern p = Pattern.compile(pattern);

    Matcher matcher = p.matcher(target);

    if(matcher.find()){

        return matcher.start();

    }

    return -1;
}

This function takes in a user provided pattern and to see if the pattern exists within the target String. Sometimes a user could include regex characters like *** hello world in the String and this causes the function to return a Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' error.

How can I treat the user generated String to overcome errors like these?

Skizit
  • 43,506
  • 91
  • 209
  • 269

1 Answers1

0

Use Pattern.quote

Pattern p = Pattern.compile(Pattern.quote(pattern));

Note: this assumes that it isn't a real regex being passed in.

public static String quote(String s)

Returns a literal pattern String for the specified String. This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.

Metacharacters or escape sequences in the input sequence will be given no special meaning.

Community
  • 1
  • 1
FDinoff
  • 30,689
  • 5
  • 75
  • 96