由多个分隔符拆分字符串

Kar*_*rma 55 ruby string split

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

  1. word.split 将被白色空间分开;

  2. word.split(",")将分裂,;

  3. word.split("\'")将分裂'.

如何一次完成这三个?

Car*_*and 126

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

  • 嘿,人们,感谢过去两年的所有赞成,但请不要忽视@oldgod的回答. (11认同)

old*_*god 38

正则表达式.

"a,b'c d".split /\s|'|,/
# => ["a", "b", "c", "d"]
Run Code Online (Sandbox Code Playgroud)

  • 我之前错过了你的答案.我更喜欢它,因为它读得更好(使用'或').你忘了包含`|\s`,可能是因为你误读了这个问题. (3认同)

Aru*_*hit 21

这是另一个:

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


Jam*_*ill 10

您可以使用split方法和Regexp.union方法的组合,如下所示:

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

你甚至可以在分隔符中使用正则表达式.

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

该解决方案具有允许完全动态分隔符或任何长度的优点.