用多个分隔符分割字符串

问题描述 投票:0回答:6

我想使用单个 ruby 命令按空格、

,
'
分割字符串。

  1. word.split
    将被空格分割;

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

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

如何同时完成这三件事?

ruby string split
6个回答
162
投票
word = "Now is the,time for'all good people"
word.split(/[\s,']/)
 => ["Now", "is", "the", "time", "for", "all", "good", "people"] 

66
投票

正则表达式。

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

39
投票

您可以结合使用

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

该解决方案的优点是允许完全动态的分隔符或任意长度。


25
投票

这是另一张:

word = "Now is the,time for'all good people"
word.scan(/\w+/)
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]
Ruby 正则表达式中的

\w+
匹配一个或多个字母数字字符。它的工作原理是找到第一个字母数字字符,然后检查下一个字符。如果下一个字符是字母数字,则它包含在匹配中。重复此过程,直到找到非字母数字字符。


4
投票
x = "one,two, three four" 

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

1
投票

我知道这是一个旧线程,但我只是偶然发现它并认为我会留下另一个答案。我个人喜欢避免使用

regex
,因为我发现它很难阅读,而且它几乎总是比使用其他内置方法慢。因此,我还会考虑使用以下解决方案,而不是上述的正则表达式解决方案:

word.gsub(",", " ").gsub("'", " ").split

第一个

gsub
将所有出现的
,
替换为
space
。第二个 gsub 将所有出现的
'
替换为
space
。这会在所有所需位置产生
whitespace
。然后
split
不带参数只是在空格上分割。

它只比上述一些解决方案稍微快一点,但我确实相信它比提到的任何其他解决方案都要快。

© www.soinside.com 2019 - 2024. All rights reserved.