如果结果包含正则表达式特殊字符,为什么我不能对扫描的每个结果执行gsub?
这是“ 包含数学符号的正则表达式有什么问题?(Ruby / Rails) ”的变体。
我无法理解为什么这个scan
后跟一个gsub
对加号( +
)不起作用。 当模式包含其他正则表达式特殊字符(如星号( *
)和插入符号( ^
))时,它也会失败。
~ > irb >> text = %(test √x+1 √x-1 √x×1 √/1) => "test √x+1 √x-1 √x×1 √/1" >> radicals = text.scan(/√[^\s]*/) => ["√x+1", "√x-1", "√x×1", "√/1"] >> radicals.each do |radical| ?> text = text.gsub(/#{radical}/, 'hello') >> end => ["√x+1", "√x-1", "√x×1", "√/1"] >> text => "test √x+1 hello hello hello"
正如您在第五行中看到的那样, scan
找到带有加号( +
)的匹配模式,但是当我尝试在每个结果上执行gsub
时,带有加号的模式将被忽略。 关于这里发生了什么的任何想法?
当您使用/#{string}/
style将/#{string}/
替换为regexp时,特殊字符(如+
)不会被转义。 我希望你想用:
radicals.each do |radical| text = text.gsub(/#{Regexp.escape(radical)}/, 'hello') end
希望这可以帮助!