简体   繁体   English

通过多个分隔符拆分字符串

[英]Split string by multiple delimiters

I want to split a string by whitespaces, , and ' using a single ruby command.我想使用单个 ruby​​ 命令按空格,'分割字符串。

  1. word.split will split by white spaces; word.split将被空格分割;

  2. word.split(",") will split by , ; word.split(",")将被,分割;

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

How to do all three at once?如何一次完成所有三个?

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

Regex. 正则表达式。

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

Here is another one : 这是另一个:

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

You can use a combination of the split method and the Regexp.union method 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. 该解决方案具有允许完全动态分隔符或任何长度的优点。

x = "one,two, three four" 

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

I know this is an old thread but I just happened to stumble on it and thought I would leave another answer.我知道这是一个旧线程,但我碰巧偶然发现它并认为我会留下另一个答案。 I personally like to avoid using regex , both because I find it hard to read and because its almost always slower than using other built in methods.我个人喜欢避免使用regex ,因为我发现它很难阅读,而且它几乎总是比使用其他内置方法慢。 So, instead of the aforementioned regex solutions, I would also consider using the following:因此,除了上述正则表达式解决方案,我还会考虑使用以下内容:

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

The first gsub replaces all occurrences of , with a space .第一gsub替换所有出现,space The second gsub replaces all occurrences of ' with a space .第二GSUB替换所有出现的'space This results in whitespace at all the desired locations.这会导致所有所需位置的whitespace And then split with an argument simply splits on whitespace.然后split与争论只是在空白分裂。

Its only slightly faster than some of the aforementioned solutions, but I do believe it is faster than any others that have been mentioned.它只比上述一些解决方案略快,但我相信它比提到的任何其他解决方案都要快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM