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

标签 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

最佳答案

使用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"]

关于Ruby - 匹配字符串中的所有模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22003531/

相关文章:

Ruby Sequel : Array returned by query is being returned as a String object, 不是数组对象

ruby - 使用 roo gem 创建 xlsx 文件

c# - 在 C# 中使用正则表达式对列表元素进行排序

JavaScript/Regex 参数具有不同的值

c# - 一种简化提供的代码的优雅方式

c - 在 C 中启动嵌套 for 循环以迭代参数的问题

ruby-on-rails - 在 Rails 中的分页 gem 中,您如何在不需要时隐藏分页?

ruby - 减少数字数组(序列)

regex - 避免使用Varnish对来自不同URI的可用项进行双重缓存

string - 如何构造具有多个具有不同生命周期的str变量的结构?