我在用 Ruby 1.9.3。我正在玩一些模式并发现一些有趣的东西:
例1:
irb(main):001:0> /hay/ =~ 'haystack'
=> 0
irb(main):003:0> /st/ =~ 'haystack'
=> 3
例2:
irb(main):002:0> /hay/.match('haystack')
=> #<MatchData "hay">
irb(main):004:0> /st/.match('haystack')
=> #<MatchData "st">
=~ 返回其第一个匹配的第一个位置,而 match 返回模式。除此之外,两者之间是否有任何区别 =~ 和 match()?
执行时间差
首先确保您使用的是正确的运算符: =~ 是正确的, ~= 不是。
运营商 =~ 返回第一个匹配的索引(nil 如果没有匹配)并存储 MatchData 在全局变量中 $~。命名捕获组被分配给哈希 $~,当, RegExp 是运算符左侧的文字,也分配给具有这些名称的局部变量。
>> str = "Here is a string"
>> re = /(?<vowel>[aeiou])/ # Contains capture group named "vowel"
>> str =~ re
=> 1
>> $~
=> #<MatchData "e" vowel:"e">
>> $~[:vowel] # Accessible using symbol...
=> "e"
>> $~["vowel"] # ...or string
=> "e"
>> /(?<s_word>\ss\w*)/ =~ str
=> 9
>> s_word # This was assigned to a local variable
=> " string"
方法 match 返回 MatchData 本身(再次, nil 如果没有匹配)。在这种情况下,在方法调用的任一侧,命名的捕获组被分配给返回的散列 MatchData。
>> m = str.match re
=> #<MatchData "e" vowel:"e">
>> m[:vowel]
=> "e"
看到 http://www.ruby-doc.org/core-1.9.3/Regexp.html (以及关于的部分) MatchData 和 String) 更多细节。
当你有一个不修改状态的方法时,重要的是返回值。那么除了颜色之外,红色和蓝色之间的区别是什么?我的观点是,这是一个奇怪的问题,你似乎已经知道了答案。 (@sawa把我直接放在这里)
但是说,这两种方法都会回归 nil (正则表达式)当正则表达式不匹配时。并且,两种方法在匹配时都会返回真值。 =~ 返回一个整数,表示匹配的第一个字符,即使是 0因为 0 在Ruby中是真的。 match 返回一个具有非常详细的匹配数据的对象,当您需要大量有关匹配的信息时,这很方便。
=~ 当你只关心时,通常用于条件 如果 匹配的东西:
do_stuff if "foobar" =~ /foo/
do_stuff if "foobar".match(/foo/) # same effect, but probably slower and harder to read
match 通常在需要有关匹配内容的详细信息时使用:
name = "name:bob".match(/^name:(\w+)$/)[1]
puts name #=> 'bob'