我想使用单个 ruby 命令按空格、
,
和 '
分割字符串。
word.split
将被空格分割; word.split(",")
将被 ,
;word.split("\'")
将被 '
分割。如何同时完成这三件事?
word = "Now is the,time for'all good people"
word.split(/[\s,']/)
=> ["Now", "is", "the", "time", "for", "all", "good", "people"]
正则表达式。
"a,b'c d".split /\s|'|,/
# => ["a", "b", "c", "d"]
您可以结合使用
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"]
该解决方案的优点是允许完全动态的分隔符或任意长度。
这是另一张:
word = "Now is the,time for'all good people"
word.scan(/\w+/)
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]
Ruby 正则表达式中的匹配一个或多个字母数字字符。它的工作原理是找到第一个字母数字字符,然后检查下一个字符。如果下一个字符是字母数字,则它包含在匹配中。重复此过程,直到找到非字母数字字符。\w+
x = "one,two, three four"
new_array = x.gsub(/,|'/, " ").split
我知道这是一个旧线程,但我只是偶然发现它并认为我会留下另一个答案。我个人喜欢避免使用
regex
,因为我发现它很难阅读,而且它几乎总是比使用其他内置方法慢。因此,我还会考虑使用以下解决方案,而不是上述的正则表达式解决方案:
word.gsub(",", " ").gsub("'", " ").split
第一个
gsub
将所有出现的 ,
替换为 space
。第二个 gsub 将所有出现的 '
替换为 space
。这会在所有所需位置产生 whitespace
。然后 split
不带参数只是在空格上分割。
它只比上述一些解决方案稍微快一点,但我确实相信它比提到的任何其他解决方案都要快。