正则表达式不转义(字面量)

本文介绍了如何在不同的Java版本中将普通字符串安全地转换为正则表达式,包括自JDK1.5起引入的方法及JDK1.4中的替代方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Since JDK 1.5, there are two simple ways to do what you want:
String safeRegex = Pattern.quote(literalString);
or
Pattern p = Pattern.compile(literalString, Pattern.LITERAL);
If you're still running JDK 1.4, the options are still relatively simple:
String safeRegex = "\\Q" + literalString + "\\E";
or
safeRegex = literalString.replaceAll("\\p{Punct}", "\\\\$0");

As for the double-backslashes-to-newlines thing, that's a stealth feature that was added to the forums couple of weeks ago. The only known way to circumvent it is to use another stealth feature: wrapping your code in [code][/code] tags before you post it.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值