为什么RegExp.escape在我的Ruby表达式中不起作用? [英] Why is RegExp.escape not working in my Ruby expression?

查看:152
本文介绍了为什么RegExp.escape在我的Ruby表达式中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Ruby 2.4。我有一些字符串包含在正则表达式中具有特殊含义的字符。所以为了消除这些字符被解释为正则表达式字符的任何可能性,我使用Regexp.escape来试图逃避它们。但是,我仍然似乎无法使正则表达式工作下面的...

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆