[英]Convert String to Regexp in Ruby
I frequently need to convert a String into a Regexp. 我经常需要将String转换为Regexp。 For many strings,
Regexp.new(string)
is sufficient. 对于许多字符串,
Regexp.new(string)
就足够了。 But if string
contains special characters, they need to be escaped: 但是,如果
string
包含特殊字符,则需要对它们进行转义:
string = "foo(bar)"
regex = Regexp.new(string) # => /foo(bar)/
!!regex.match(string) # => false
The Regexp class has a nice way to escape all characters that are special to regex: Regexp.escape
. Regexp类有一个很好的方法来转义所有regex特殊字符:
Regexp.escape
。 It's used like so: 它的用法如下:
string = "foo(bar)"
escaped_string = Regexp.escape(string) # => "foo\\(bar\\)"
regex = Regexp.new(escaped_string) # => /foo\(bar\)/
!!regex.match(string) # => true
This really seems like this should be the default way Regexp.new
works. 这似乎真的应该是
Regexp.new
的默认工作方式。 Is there a better way to convert a String to a Regexp, besides Regexp.new(Regexp.escape(string))
? 除了
Regexp.new(Regexp.escape(string))
之外,是否还有更好的方法将String转换为Regexp? This is Ruby, after all. 毕竟是 Ruby。
You should never need to run Regexp.new(Regexp.escape(string))
This is because, in Core and StdLib, practically every method that takes a Regexp also takes a String (as it should). 您永远不需要运行
Regexp.new(Regexp.escape(string))
这是因为在Core和StdLib中,几乎每个采用Regexp的方法也都采用了String(应该这样做)。
In the original case, if you're trying to match a big String big_string
on a wacky string with special characters like "foo(bar)"
, you can just run big_string.match("foo(bar)")
. 在原始情况下,如果您要尝试在古怪的字符串
big_string
大字符串big_string
与特殊字符(例如"foo(bar)"
匹配,则只需运行big_string.match("foo(bar)")
。
If you're trying to do something fancier, you might need use both ::escape
and ::new
, but never in direct composition. 如果您想做一些更奇特的事情,则可能需要同时使用
::escape
和::new
,但切勿直接使用。 For example, if we want to match big_string
on a wacky string followed by a lone digit, we'll run Regexp.new(Regexp.escape(string) + "\\\\d")
. 例如,如果要在古怪的字符串上匹配
big_string
,后跟一个单数,我们将运行Regexp.new(Regexp.escape(string) + "\\\\d")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.