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]"
精彩评论