如何在Java中为正则表达式转义文本

Java是否有内置的方法来转义任意文本,以便它可以包含在正则表达式中? 例如,如果我的用户输入“$ 5”,我希望在输入结束后匹配它,而不是“5”。


从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/76781.html

上一篇: How to escape text for regular expression in Java

下一篇: Regex for number with decimals and thousand separator