How to escape text for regular expression in Java

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 exactly rather than a "5" after the end of input.


从Java 1.5开始,是的:

Pattern.quote("$5");

在我看到下面的例子之前, Pattern.quoteMatcher.quoteReplacement之间的Matcher.quoteReplacement并不清楚

s.replaceFirst(Pattern.quote("text to replace"), 
               Matcher.quoteReplacement("replacement text"));

回应可能为时已晚,但您也可以使用Pattern.LITERAL ,它可以在格式化时忽略所有特殊字符:

Pattern.compile(textToFormat, Pattern.LITERAL);
链接地址: http://www.djcxy.com/p/76782.html

上一篇: 正则表达式匹配外部括号

下一篇: 如何在Java中为正则表达式转义文本