如何从结果中获取拆分令牌?

时间:2017-03-18 19:12:50

标签: ruby string split

使用Ruby 2.4。我想将我的字符串拆分为破坏或不间断的空格,但是,下面的表达式

str = "aa 11:22 bb 33.44:55 cc dd 123"
#=> "aa 11:22 bb 33.44:55 cc dd 123"
str.split(/(\t|[[:space:]])+/)
#=> ["aa", " ", "11:22", " ", "bb", " ", "33.44:55", " ", "cc", " ", "dd", " ", "123"]

在结果中包含空格。如何进行拆分以使结果中不包含空格?

2 个答案:

答案 0 :(得分:2)

componentDidMount: function() {
  this.ref = new Firebase('<url>');
  this.bindAsArray(this.ref, 'notes');
},
handleAddNote: function(newNote) {
  this.ref.child(this.state.notes.length).set(newNote);
}...

对于您的测试数据,只需str.split(/[[:space:]]/) #=> ["aa", "11:22", "bb", "33.44:55", "cc", "dd", "123"] 即可:

split

使用不同的输入字符串的几个选项:

str.split
#=> ["aa", "11:22", "bb", "33.44:55", "cc", "dd", "123"]

答案 1 :(得分:1)

您的数组中有" ",因为(\t|[[:space:]])是一个捕获组。使用非捕获组:

str.split(/(?:\t|[[:space:]])+/)
  #=> ["aa", "11:22", "bb", "33.44:55", "cc", "dd", "123"]

请参阅String#split

如果要在中断或不中断空格上进行拆分,并且不希望在结果数组的开头或结尾处使用相同的字符串,则可以执行以下操作。

str = " \u00A0aa\t11:22\u00A0bb 33.44:55 cc dd 123  "

str.gsub(/\A[[:space:]]+|[[:space:]]+\z/,'').split(/[[:space:]]+/)
  #=> ["aa", "11:22", "bb", "33.44:55", "cc", "dd", "123"]