如何转义正则表达式 ***(.*) 中的特殊字符

发布于 2024-12-21 20:35:30 字数 208 浏览 1 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

软糖 2024-12-28 20:35:30

从表面上看,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文