Ruby - 匹配字符串中的所有模式

时间:2014-02-25 02:39:08

标签: ruby regex string

需要帮助匹配字符串中的所有模式。

s1 = " countries like US, Japan, Korea, Vietnam, Germany"
s2 = " countries like Holland, China, Korea, Thailand, UK"

从上面的字符串需要匹配特定的亚洲国家

regex = /(Japan)|(Korea)|(Vietnam)|(Cambodia)|(China)|(Thailand)/


irb(main):157:0> s1.match(regex)
=> #<MatchData "Japan" 1:"Japan" 2:nil 3:nil 4:nil>

有没有办法获得以下输出?

s1.some_regex_operation # => Japan, Korea, Vietnam
s2.some_regex_operation # => China, Korea, Thailand

1 个答案:

答案 0 :(得分:5)

使用String#scan

s1 = " countries like US, Japan, Korea, Vietnam, Germany"
s2 = " countries like Holland, China, Korea, Thailand, UK"
s1.scan(/Japan|Korea|Vietnam|Cambodia|China|Thailand/)
# => ["Japan", "Korea", "Vietnam"]
s2.scan(/Japan|Korea|Vietnam|Cambodia|China|Thailand/)
# => ["China", "Korea", "Thailand"]