开发者

How to regex match with a run-time parameter?

开发者 https://www.devze.com 2023-03-28 16:29 出处:网络
I\'ve got a string entered by the user, and I want to embed that string into a regex. Is there a way to embed a parameter value in a similar way to parameters in SQL queries?

I've got a string entered by the user, and I want to embed that string into a regex. Is there a way to embed a parameter value in a similar way to parameters in SQL queries?

For example, I could do this:

string myRegex = "[abc]" + myParameter + "[xyz]";   

but this would not work because myParameter could contain regex special characters.

SQL injection was fixed by using parameters. How do I do the same with regexes?

Note that myParameter could contain any character from the whole of unicode except maybe contro开发者_如何学Pythonl characters, although I would hope a general purpose solution would allow even control characters to be matched.


Depends on the regular expression engine at hand I believe.

In Java you typically do

"[abc]" + Pattern.quote(myParameter) + "[xyz]"

or (if myParameter doesn't contain \E) you could do

"[abc]\\Q" + myParameter + "\\E[xyz]"
0

精彩评论

暂无评论...
验证码 换一张
取 消