如何避免正则表达式中的特殊字符***(。*) [英] How to escape special characters in the regex ***(.*)

查看:264
本文介绍了如何避免正则表达式中的特殊字符***(。*)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手。有人可以帮助我吗?



Java中是否有可用的方法可以自动转义下面的正则表达式中的特殊字符?



在转义 ***(。*) 之后,转义 \\ * \\\ * \\ *(。*)



我不想逃脱(。*)

解决方案

表面上, Pattern.quote 但是,看看你的问题的细节,似乎你希望/期望能够逃脱一些元字符,而不是其他的。 Pattern.quote 将不会将其应用于单个字符串。相反,它会引用每一个字符。 (对于记录,它不使用反斜杠,它使用\E和\Q.\它可以避免解析字符串以查找需要转义的字符的费用。)



但真正的问题是你没有说出引用者应该如何决定哪些元字符要逃脱,哪些元素要完整无缺。例如,它如何知道逃避前三个em字符,而不是。?



没有更清晰的规范,你的问题是不可接受的。即使有规定,几乎没有机会找到一个简单的方法来做到这一点。



IMO,一个更好的方法是在组装模式之前进行转义从它的组成部分...假设这是发生了什么。


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.

解决方案

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.

这篇关于如何避免正则表达式中的特殊字符***(。*)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆