-1

我正在使用 Ruby 进行简单的子字符串类型匹配。我试图了解为什么会发生以下情况:

irb(main):024:0> puts "match" if "foo" =~ /foo/
match
=> nil
irb(main):025:0> puts "match" if "foo" =~ /foo,/
=> nil

如何修改此正则表达式,以便如果搜索条件的任何部分与“foo”匹配,则进行匹配?

4

2 回答 2

1

You've got your comparisons backwards:

"foo".match(/foo,/) # See if "foo" matches the pattern "foo,"
# => nil
"foo,".match(/foo/) # See if "foo," matches the pattern "foo"
# => #<MatchData "foo"> 

The =~ operator is a bit of history that has fallen out of style because it's not self-explanatory.

于 2012-11-14T04:03:59.703 回答
-2

您可以使用 String 的 scan 方法并传入要检查的正则表达式。

1.9.3p194 :008 > puts "match" if "foo".scan(/foo,/)
match
=> nil 
于 2012-11-14T01:14:56.217 回答