由多个分隔符拆分字符串

时间:2013-10-22 04:59:27

标签: ruby string split

我想使用单个ruby命令按空格分隔字符串,'

  1. word.split会被空格分开;

  2. word.split(",")将按,;

  3. 拆分
  4. word.split("\'")将按'分割。

  5. 如何一次完成所有这三项?

5 个答案:

答案 0 :(得分:115)

word = "Now is the,time for'all good people"
word.split(/[\s,']/)
 => ["Now", "is", "the", "time", "for", "all", "good", "people"] 

答案 1 :(得分:34)

正则表达式。

"a,b'c d".split /\s|'|,/
# => ["a", "b", "c", "d"]

答案 2 :(得分:19)

这是另一个:

word = "Now is the,time for'all good people"
word.scan(/\w+/)
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]

答案 3 :(得分:8)

您可以像这样使用split方法和Regexp.union方法的组合:

delimiters = [',', ' ', "'"]
word.split(Regexp.union(delimiters))
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]

您甚至可以在定界符中使用正则表达式。

delimiters = [',', /\s/, "'"]
word.split(Regexp.union(delimiters))
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]

此解决方案的优势在于允许使用完全动态的定界符或任意长度。

答案 4 :(得分:3)

x = "one,two, three four" 

new_array = x.gsub(/,|'/, " ").split