模式匹配时=〜和match()之间有什么区别?

DoL*_*Sky 12 ruby regex ruby-1.9.3

我在用Ruby 1.9.3.我正在玩一些模式,发现了一些有趣的东西:

例1:

irb(main):001:0> /hay/ =~  'haystack'
=> 0
irb(main):003:0> /st/ =~ 'haystack'
=> 3
Run Code Online (Sandbox Code Playgroud)

例2:

irb(main):002:0> /hay/.match('haystack')
=> #<MatchData "hay">
irb(main):004:0> /st/.match('haystack')
=> #<MatchData "st">
Run Code Online (Sandbox Code Playgroud)

=~返回其第一个匹配的第一个位置,而match返回该模式.除此之外,=~和之间有什么区别match()吗?

执行时间差 (根据@Casper)

irb(main):005:0> quickbm(10000000) { "foobar" =~ /foo/ }
Rehearsal ------------------------------------
   8.530000   0.000000   8.530000 (  8.528367)
--------------------------- total: 8.530000sec

       user     system      total        real
   8.450000   0.000000   8.450000 (  8.451939)
=> nil

irb(main):006:0> quickbm(10000000) { "foobar".match(/foo/) }
Rehearsal ------------------------------------
  15.360000   0.000000  15.360000 ( 15.363360)
-------------------------- total: 15.360000sec

       user     system      total        real
  15.240000   0.010000  15.250000 ( 15.250471)
=> nil
Run Code Online (Sandbox Code Playgroud)

Rei*_*ard 9

首先确保你使用的是正确的算子:=~是正确的,~=不是.

运算符=~返回第一个匹配的索引(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"
Run Code Online (Sandbox Code Playgroud)

该方法match返回MatchData自身(同样,nil如果不匹配).在这种情况下,在方法调用的任一侧,命名捕获组被分配给返回的散列MatchData.

>> m = str.match re
=> #<MatchData "e" vowel:"e">
>> m[:vowel]
=> "e"
Run Code Online (Sandbox Code Playgroud)

http://www.ruby-doc.org/core-1.9.3/Regexp.html(以及在部分MatchDataString)了解更多详情.