Do I always need to escape metacharacters in a string that is not a “literal”?

后端 未结 4 1529
耶瑟儿~
耶瑟儿~ 2021-01-12 13:53

It seems that having a string that contains the characters { or } is rejected during regex processing. I can understand that these are reserved cha

4条回答
  •  广开言路
    2021-01-12 14:29

    You don't need any extra code, just the \Q and \E constructs, as documented in Java's Pattern class.

    For example, in the following code:

    String foobar = "crazyPassword=f()ob@r{}+";
    Pattern regex = Pattern.compile("\\Q" + foobar "\\E");
    

    the pattern would compile and foobar's special characters would not be interpreted as regex characters. See demo here.

    The only thing that it won't match is where the input contains a literal \E. If you need to solve that problem too, just let me know in a comment and I'll edit to add that.

提交回复
热议问题