How to escape text for regular expression in Java

前端 未结 8 1815
我在风中等你
我在风中等你 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"));
    
    0 讨论(0)
  • 2020-11-22 03:54

    Difference between Pattern.quote and Matcher.quoteReplacement was not clear to me before I saw following example

    s.replaceFirst(Pattern.quote("text to replace"), 
                   Matcher.quoteReplacement("replacement text"));
    
    0 讨论(0)
提交回复
热议问题