如何转义正则表达式 ***(.*) 中的特殊字符
我是 Java 新手。有人可以帮助我吗?
Java中是否有任何方法可以自动转义下面的正则表达式中的特殊字符?
转义 ***(.*)
之前和转义 \\*\\*\\*(.*)
< /strong>
我不想在这里转义 (.*)。
I am new to Java. Can somebody help me?
Is there any method available in Java which escapes the special characters in the below regex automatically?
Before escaping ***(.*)
and after escaping \\*\\*\\*(.*)
I don't want to escape (.*) here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从表面上看,
Pattern.quote
似乎可以完成这项工作。然而,看看你的问题的细节,你似乎希望/期望能够转义一些元字符而不是其他元字符。如果将
Pattern.quote
应用于单个字符串,则不会这样做。相反,它会引用每个字符。 (根据记录,它不使用反斜杠。它使用“\E”和“\Q”。\ 这巧妙地避免了解析字符串以查找需要转义的字符的成本。)但真正的问题是你还没有没有说引用者应该如何决定哪些元字符要转义以及哪些元字符要完整保留。例如,它如何知道转义前三个“”字符,而不是“.”?
如果没有更清晰的规范,您的问题几乎无法回答。即使有了规范,也几乎没有机会找到一种简单的方法来做到这一点。
IMO,更好的方法是在从其组成部分组装模式之前进行转义......假设这就是这里发生的情况。
On the face of it,
Pattern.quote
appears to do the job.However, looking at the detail of your question, it appears that you want / expect to be able to escape some meta-characters and not others.
Pattern.quote
won't do that if you apply it to a single string. Rather, it will quote each and every character. (For the record, it doesn't use backslashes. It uses "\E" and "\Q".\ which neatly avoids the cost of parsing the string to find characters that need escaping.)But the real problem is that you haven't said how the quoter should decide which meta-characters to escape and which ones to leave intact. For instance, how does it know to escape the first three '' characters, but not the "."?
Without a clearer specification, your question is pretty much unanswerable. And even with a specification, there is little chance of finding an easy way to do this.
IMO, a better approach would be to do the escaping before you assemble the pattern from its component parts ... assuming that's what is going on here.