如何在不保留分隔符的情况下拆分字符串?
How do I split a string without keeping the delimiter?
在 Ruby 中,如何拆分字符串而不在生成的拆分数组中保留分隔符?我以为这是默认设置,但是当我尝试
2.4.0 :016 > str = "a b c"
=> "a b c"
2.4.0 :017 > str.split(/([[:space:]]|,)+/)
=> ["a", " ", "b", " ", "c"]
我看到结果中包含空格。我希望结果只是
["a", "b", "c"]
请试试这个
str.split(' ')
来自 String#split
文档:
If pattern contains groups, the respective matches will be returned in the array as well.
回答您明确提出的问题:不匹配组:
# ⇓⇓ HERE
str.split(/(?:[[:space:]]|,)+/)
或者,即使没有组:
str.split(/[[:space:],]+/)
或者,更像 Rubyish 的方式:
'a b, c,d e'.split(/[\p{Space},]+/)
#⇒ ["a", "b", "c", "d", "e"]
String#split
默认在白色上拆分-space,所以不要为正则表达式而烦恼:
"a b c".split # => ["a", "b", "c"]
在 Ruby 中,如何拆分字符串而不在生成的拆分数组中保留分隔符?我以为这是默认设置,但是当我尝试
2.4.0 :016 > str = "a b c"
=> "a b c"
2.4.0 :017 > str.split(/([[:space:]]|,)+/)
=> ["a", " ", "b", " ", "c"]
我看到结果中包含空格。我希望结果只是
["a", "b", "c"]
请试试这个
str.split(' ')
来自 String#split
文档:
If pattern contains groups, the respective matches will be returned in the array as well.
回答您明确提出的问题:不匹配组:
# ⇓⇓ HERE
str.split(/(?:[[:space:]]|,)+/)
或者,即使没有组:
str.split(/[[:space:],]+/)
或者,更像 Rubyish 的方式:
'a b, c,d e'.split(/[\p{Space},]+/)
#⇒ ["a", "b", "c", "d", "e"]
String#split
默认在白色上拆分-space,所以不要为正则表达式而烦恼:
"a b c".split # => ["a", "b", "c"]