Ruby, weird substitution
For example:
开发者_运维知识库str1 = "pppp(m)pppp"
str2 = "(m)"
str1 = str1.sub(/#{str2}/, "<>#{str2}<>")
I will got this:
"pppp(<>(m)<>)pppp"
I expected to get this:
"pppp<>(m)<>pppp"
Why it's happening and how to avoid this?
In (
and )
have a special meaning in regexen and do not actually match the characters (
and )
. The regex /(m)/
will match any m
whether or not it is enclosed in parentheses (and if it is, it won't match the parentheses).
To match literal parentheses use \(
and \)
- or in a case like this where you're interpolating a string, you can just use Regexp.escape
on the string, i.e. /#{ Regexp.escape(str2) }/
.
The regular expression is viewing the "(m)"
as a capture group because the parenthesis are operators in regular expressions to get a literal "(m)"
you need to use the escape char \
["\(m\)"
].
精彩评论