I am trying to find matches in some code using regex.
String I am using
"input[type=radio],input[type=checkbox] {"
To match this I added escape characters for every bracket:
"input\[type=radio\],input\[type=checkbox\] \{"
And I am running .match to find a match in a particular line of code:
"input[type=radio],input[type=checkbox] {".match(/input\[type=radio\],input\[type=checkbox\] \{/)
Which works. But when I turn them into variables, it doesn’t.
str = "input[type=radio],input[type=checkbox] {"
code_to_match_against = "input\[type=radio\],input\[type=checkbox\] \{"
str.match(/#{code_to_match_against}/) # => nil
What am I doing wrong?
The double quotes in here:
are eating your backslashes. Consider this:
So when you interpolate
code_to_match_againstinto your regex, the regex engine thinks you’re using two character classes:and character classes match only one character at a time (unless you append
*or+).Either double your backslashes to get them past the double quotes or use single quotes instead: