How to escape special characters in the regex ***(.*)

ぃ、小莉子 提交于 2020-01-03 15:54:10

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8573662/how-to-escape-special-characters-in-the-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!