如何使用变量通过正则表达式来匹配这段代码?

时间:2012-10-09 01:08:46

标签: ruby regex

我正在尝试使用正则表达式在某些代码中找到匹配项。

我正在使用的字符串

"input[type=radio],input[type=checkbox] {"

为了匹配这一点,我为每个括号添加了转义字符:

"input\[type=radio\],input\[type=checkbox\] \{"

我正在运行.match以查找特定代码行中的匹配项:

"input[type=radio],input[type=checkbox] {".match(/input\[type=radio\],input\[type=checkbox\] \{/)

哪个有效。但是当我把它们变成变量时,却没有。

str = "input[type=radio],input[type=checkbox] {"
code_to_match_against = "input\[type=radio\],input\[type=checkbox\] \{"

str.match(/#{code_to_match_against}/) # => nil

我做错了什么?

1 个答案:

答案 0 :(得分:3)

这里的双引号:

code_to_match_against = "input\[type=radio\],input\[type=checkbox\] \{"

正在吃你的反斜杠。考虑一下:

>> code_to_match_against = "input\[type=radio\],input\[type=checkbox\] \{"
>> p code_to_match_against
"input[type=radio],input[type=checkbox] {"

因此,当您将code_to_match_against插入到正则表达式中时,正则表达式引擎会认为您正在使用两个字符类:

/input[type=radio],input[type=checkbox] {/
#     ^^^^^^^^^^^^      ^^^^^^^^^^^^^^^

和字符类一次只匹配一个字符(除非您追加*+)。

要么加倍反斜杠以使它们超过双引号或改为使用单引号:

>> code_to_match_against = 'input\[type=radio\],input\[type=checkbox\] \{'
>> p code_to_match_against
"input\\[type=radio\\],input\\[type=checkbox\\] \\{"
>> puts code_to_match_against
input\[type=radio\],input\[type=checkbox\] \{