How to escape text for regular expression in Java

前端 未结 8 1930
我在风中等你
我在风中等你 2020-11-22 03:30

Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter \"$5\", I\'d like to match that exa

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 03:53

    Pattern.quote("blabla") works nicely.

    The Pattern.quote() works nicely. It encloses the sentence with the characters "\Q" and "\E", and if it does escape "\Q" and "\E". However, if you need to do a real regular expression escaping(or custom escaping), you can use this code:

    String someText = "Some/s/wText*/,**";
    System.out.println(someText.replaceAll("[-\\[\\]{}()*+?.,\\\\\\\\^$|#\\\\s]", "\\\\$0"));
    

    This method returns: Some/\s/wText*/\,**

    Code for example and tests:

    String someText = "Some\\E/s/wText*/,**";
    System.out.println("Pattern.quote: "+ Pattern.quote(someText));
    System.out.println("Full escape: "+someText.replaceAll("[-\\[\\]{}()*+?.,\\\\\\\\^$|#\\\\s]", "\\\\$0"));
    

提交回复
热议问题