ruby 通过多个分隔符拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19509307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split string by multiple delimiters
提问by Karan Verma
I want to split a string by whitespaces, ,and 'using a single ruby command.
我想用空格分割一个字符串,,并'使用一个 ruby 命令。
word.splitwill split by white spaces;word.split(",")will split by,;word.split("\'")will split by'.
word.split将被空格分割;word.split(",")将分裂为,;word.split("\'")将被'.
How to do all three at once?
如何一次完成所有三个?
回答by Cary Swoveland
word = "Now is the,time for'all good people"
word.split(/[\s,']/)
=> ["Now", "is", "the", "time", "for", "all", "good", "people"]
回答by oldergod
Regex.
正则表达式。
"a,b'c d".split /\s|'|,/
# => ["a", "b", "c", "d"]
回答by Arup Rakshit
Here is another one :
这是另一个:
word = "Now is the,time for'all good people"
word.scan(/\w+/)
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]
回答by James Stonehill
You can use a combination of the splitmethod and the Regexp.unionmethod like so:
您可以像这样使用split方法和Regexp.union方法的组合:
delimiters = [',', ' ', "'"]
word.split(Regexp.union(delimiters))
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]
You can even use regex patters in the delimiters.
您甚至可以在分隔符中使用正则表达式模式。
delimiters = [',', /\s/, "'"]
word.split(Regexp.union(delimiters))
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]
This solution has the advantage of allowing totally dynamic delimiters or any length.
该解决方案的优点是允许完全动态的定界符或任何长度。
回答by Beartech
x = "one,two, three four"
new_array = x.gsub(/,|'/, " ").split

