Kar*_*rma 55 ruby string split
我想用空格分割字符串,,并'使用单个ruby命令.
word.split 将被白色空间分开;
word.split(",")将分裂,;
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)
old*_*god 38
正则表达式.
"a,b'c d".split /\s|'|,/
# => ["a", "b", "c", "d"]
Run Code Online (Sandbox Code Playgroud)
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)
该解决方案具有允许完全动态分隔符或任何长度的优点.