通过正则表达式将单词标记为数组

时间:2014-01-23 20:00:58

标签: ruby-on-rails ruby regex

我有以下地址:

  

1330 City Street,PO BOX 444 ---第7,8,9和13号部分,~~~惠灵顿中心镇(Elora村),   惠灵顿县

我想用逗号结尾标记每个单词。在上面的例子中,我们将标记以下内容:

1330 City Street
PO BOX 444 ---第7部分 8
9
和13
~~~惠灵顿中心镇(伊洛拉村)

我想用红宝石做。任何帮助将不胜感激

3 个答案:

答案 0 :(得分:0)

你可以这样做:

s = "1330 City Street, PO BOX 444 --- Parts 7,8,9, and 13,~~~Centre Wellington Township (Village of Elora), County of Wellington"

s.split(',').last.strip # => "County of Wellington"

答案 1 :(得分:0)

这个也很方便。它删除逗号后的最后一个标记,然后执行拆分。

input = '1330 City Street, PO BOX 444 --- Parts 7,8,9, and 13,~~~Centre Wellington Township (Village of Elora), County of Wellington'
print input.gsub(/[^,]*$/, "").split(/,/)

答案 2 :(得分:0)

我会这样做:

s = "1330 City Street, PO BOX 444 --- Parts 7,8,9, and 13,~~~Centre Wellington Township (Village of Elora), County of Wellington"
s.scan(/[^,]+(?=[,])/).map(&:strip)
# => ["1330 City Street",
#     "PO BOX 444 --- Parts 7",
#     "8",
#     "9",
#     "and 13",
#     "~~~Centre Wellington Township (Village of Elora)"]
puts s.scan(/[^,]+(?=[,])/).map(&:strip)

# >> 1330 City Street
# >> PO BOX 444 --- Parts 7
# >> 8
# >> 9
# >> and 13
# >> ~~~Centre Wellington Township (Village of Elora)

也可以在Rubular.com

中查看