是否有另一种方法可以在不使用字符串转义所有字符的情况下执行正则表达式?
我有这行代码来删除一些标点符号:
str.replaceAll("[\\-\\!\\?\\.\\,\\;\\:\\\"\\']", "");
我不知道这个正则表达式中的所有字符是否都需要转义,但我只是为了安全而转义。
有没有办法以更清晰的方式构建这样的正则表达式?
I have this line of code to remove some punctuation:
str.replaceAll("[\\-\\!\\?\\.\\,\\;\\:\\\"\\']", "");
I don't know if all the chars in this regex need to be escaped, but I escaped only for safety.
Is there some way to build a regex like this in a more clear way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
[
...]
内,您不需要转义字符。例如[.]
无论如何都是没有意义的!该规则的例外是
]
,因为它会过早关闭整个[...]
表达式。^
如果它是第一个字符,因为[^abc]
匹配除了abc
之外的所有内容。-
除非它是第一个/最后一个字符,因为[az]
匹配a
到z
之间的所有字符。因此,您可以编写
将字符串引用到正则表达式中,还可以使用
Pattern.quote
来根据需要转义字符串中的字符。演示:
Inside
[
...]
you don't need to escape the characters.[.]
for instance wouldn't make sense anyway!The exceptions to the rule are
]
since it would close the whole[...]
expression prematurely.^
if it is the first character, since[^abc]
matches everything exceptabc
.-
unless it's the first/last character, since[a-z]
matches all characters betweena
toz
.Thus, you could write
To quote a string into a regular expression, you could also use
Pattern.quote
which escapes the characters in the string as necessary.Demo:
您可能需要转义双引号,因为字符串用双引号引起来;但正如 aioobe 所说,不要逃避其余的事情。但是,请将
-
放在组的末尾。You might need to escape the double-quotes because you have the string in double-quotes; but as aioobe says, don't escape the rest. Put the
-
at the end of the group, however.