Ruby str.match(regex) returns MatchData 仅包含第一个匹配项
Ruby str.match(regex) returns MatchData containing only first matched item
使用Ruby 2.2
我有如下字符串:
- 每周二和周五
- 每周一、周三和周六
- 每月每 2 周的星期一
为了从上面显示的字符串中提取星期几,我编写了以下正则表达式:
/\b(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\b/
当尝试使用 String#match
实例方法时,match_data 不会 return 所有匹配项。例如请参考下面显示的 irb 输出,其中当字符串 Weekly on Tuesday and Friday
与上面显示的正则表达式匹配时,MatchData
仅包含 Tuesday
。我希望它也包含 Friday
。
2.2.1 :001 > str = "Weekly on Tuesday and Friday"
=> "Weekly on Tuesday and Friday"
2.2.1 :002 > regex = /\b(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\b/
=> /\b(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\b/
2.2.1 :003 > str.match(regex)
=> #<MatchData "Tuesday" 1:"Tuesday">
2.2.1 :004 > match_data = str.match(regex)
=> #<MatchData "Tuesday" 1:"Tuesday">
2.2.1 :005 > match_data.captures
=> ["Tuesday"]
任何人都可以解释为什么 MatchData 只包含第一个匹配的术语,而我没有在我的正则表达式中使用任何 start/end 锚点吗?我确定我的正则表达式遗漏了一些东西,但我无法弄清楚。
备注
Rubular 显示相同正则表达式的正确匹配组,如 http://rubular.com/r/XZmrHPkjEk
所示
.match()
方法返回的 MatchData
似乎只是 returns 与所有捕获组的第一个匹配项(如果有的话)。我刚刚测试了它,但我只能得到 1 个与 .match()
.
的匹配项
To test if a particular regex matches (part of) a string, you can
either use the =~ operator, call the regexp object's match() method,
e.g.: print "success" if subject =~ /regex/ or print "success" if
/regex/.match(subject).
此外,来自 here:
String.=~(Regexp)
returns the starting position of the first match or
nil if no match was found
要获取所有匹配项,需要使用.scan()
方法。
使用Ruby 2.2
我有如下字符串:
- 每周二和周五
- 每周一、周三和周六
- 每月每 2 周的星期一
为了从上面显示的字符串中提取星期几,我编写了以下正则表达式:
/\b(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\b/
当尝试使用 String#match
实例方法时,match_data 不会 return 所有匹配项。例如请参考下面显示的 irb 输出,其中当字符串 Weekly on Tuesday and Friday
与上面显示的正则表达式匹配时,MatchData
仅包含 Tuesday
。我希望它也包含 Friday
。
2.2.1 :001 > str = "Weekly on Tuesday and Friday"
=> "Weekly on Tuesday and Friday"
2.2.1 :002 > regex = /\b(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\b/
=> /\b(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\b/
2.2.1 :003 > str.match(regex)
=> #<MatchData "Tuesday" 1:"Tuesday">
2.2.1 :004 > match_data = str.match(regex)
=> #<MatchData "Tuesday" 1:"Tuesday">
2.2.1 :005 > match_data.captures
=> ["Tuesday"]
任何人都可以解释为什么 MatchData 只包含第一个匹配的术语,而我没有在我的正则表达式中使用任何 start/end 锚点吗?我确定我的正则表达式遗漏了一些东西,但我无法弄清楚。
备注
Rubular 显示相同正则表达式的正确匹配组,如 http://rubular.com/r/XZmrHPkjEk
所示.match()
方法返回的 MatchData
似乎只是 returns 与所有捕获组的第一个匹配项(如果有的话)。我刚刚测试了它,但我只能得到 1 个与 .match()
.
To test if a particular regex matches (part of) a string, you can either use the =~ operator, call the regexp object's match() method, e.g.: print "success" if subject =~ /regex/ or print "success" if /regex/.match(subject).
此外,来自 here:
String.=~(Regexp)
returns the starting position of the first match or nil if no match was found
要获取所有匹配项,需要使用.scan()
方法。