为什么RegExp.escape在我的Ruby表达式中不起作用? [英] Why is RegExp.escape not working in my Ruby expression?
问题描述
2.4.0:005> tokens = [a,b?,c]
=> [a,b?,c]
2.4.0:006> line =1\ta\tb?\tc\t3
=> 1\ta\tb?\tc\t3
2.4.0:009> /#{Regexp.escape(tokens.join())。gsub(,\\s +)} /。match(line)
=> nil
在用\s +表达式替换空格之前,如何正确地转义字符,我想要解释为正则表达式字符?
当 Regexp.escape(tokens.join ())gsub(,\\\ss)
执行 tokens.join()
AB? c
,然后转义字符串 - > a\ b\?\ c
,然后 gsub执行
导致 a\\ss + b\?\\s + c
。现在,行
是 1 a b? c 3
。所以,所有 \\
现在匹配一个字面反斜杠,它们不再形成一个特殊的正则表达式元字符匹配空格。
您需要转义令牌,并加入 \s +
,或加入空格,然后用 \s + / code>:
/#{tokens.map {| n | Regexp.escape(n)} .join(\\s +)} /。match(line)
OR
/#{tokens.map {| n | Regexp.escape(n)} .join().gsub(,\\ss)} /。match(line)
I'm using Ruby 2.4. I have some strings that contain characters that have special meaning in regular expression. So to eliminate any possibility of those characters being interpreted as regexp characters, I use the "Regexp.escape" to attempt to escape them. However, I still seem unable to make teh below regular expression work ...
2.4.0 :005 > tokens = ["a", "b?", "c"]
=> ["a", "b?", "c"]
2.4.0 :006 > line = "1\ta\tb?\tc\t3"
=> "1\ta\tb?\tc\t3"
2.4.0 :009 > /#{Regexp.escape(tokens.join(" ")).gsub(" ", "\\s+")}/.match(line)
=> nil
How can I properly escape the characters before substituting the space with a "\s+" expression, whcih I do want interpreted as a regexp character?
When the Regexp.escape(tokens.join(" ")).gsub(" ", "\\s+")
is executed, tokens.join(" ")
yields a b? c
, then the string is escaped -> a\ b\?\ c
, and then the gsub
is executed resulting in a\\s+b\?\\s+c
. Now, line
is 1 a b? c 3
. So, all \\
are now matching a literal backslash, they no longer form an special regex metacharacter matching whitespace.
You need to escape the tokens, and join with \s+
, or join with space and later replace the space with \s+
:
/#{tokens.map { |n| Regexp.escape(n) }.join("\\s+")}/.match(line)
OR
/#{tokens.map { |n| Regexp.escape(n) }.join(" ").gsub(" ", "\\s+")}/.match(line)
这篇关于为什么RegExp.escape在我的Ruby表达式中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!