简体   繁体   English

红宝石中的每个第一个空格分割字符串

[英]Split string by every first space in ruby

I have a string: 我有一个字符串:

"AB C   D E   F"

I need to split it into an array so that it looks like: 我需要将其拆分为一个数组,使其看起来像:

[AB][C][ ][D][E][ ][F]

The most I can find online is splitting by " ", which gets rid of every space, and another way that only splits by the first space in the entire string. 我在网上最多能找到的是用“”分割,它消除了每个空格,而另一种方式是只分割整个字符串中的第一个空格。

Maybe using scan would give you your expected output easier: 也许使用scan可以使您的预期输出更容易:

p str.scan(/[A-Z]+|\s{3}/)
# ["AB", "C", "   ", "D", "E", "   ", "F"]

As your input is only capitalized characters, [AZ] would work, /[az]/i is for both cases. 由于您的输入仅是大写字母,因此[AZ]可以使用, /[az]/i两种情况都适用。

Wondering why such an output: 想知道为什么这样的输出:

p str.scan(/[A-Z]+|\s{3}/).map(&:split)
# [["AB"], ["C"], [], ["D"], ["E"], [], ["F"]]

split on spaces. 在空格上分割。

str="A B C  D E  F".split(/\s/)
#=> ["A", "B", "C", "", "D", "E", "", "F"]

or 要么

str="A B C  D E  F".split(/\s|[a-z]/)
#=> ["A", "B", "C", "", "D", "E", "", "F"]

to prove that it works, split on spaces, join on space, and then split on spaces again. 为了证明它有效,请在空间上拆分,在空间上合并,然后再次在空间上拆分。 Control chars remain unaffected :) 控制字符不受影响:)

str="A B C  D E  F".split(/\s|[a-z]/).join(" ").split(/\s|[a-z]/)
#=> ["A", "B", "C", "", "D", "E", "", "F"]

Other variations/options to explore: 要探索的其他变体/选项:

str="A B C  D E  F".split(/(\s)/)
#=> ["A", " ", "B", " ", "C", " ", "", " ", "D", " ", "E", " ", "", " ", "F"]

str="A B C  D E  F".split(//)
#=> ["A", " ", "B", " ", "C", " ", " ", "D", " ", "E", " ", " ", "F"]
"AB C   D E   F".scan(/\S+|\s{2,}/)
#=> ["AB", "C", "   ", "D", "E", "   ", "F"]

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

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