Why can't I split a string on control characters?

 ̄綄美尐妖づ 提交于 2019-12-11 20:14:38

问题


I am trying to split a line when I find the characters ^C or ^B together. For some reason it is not splitting properly.

I have been on Rubular and tested this and supposedly it should split it.

The lines that I am reading in and trying to split look something like this:

SOME_KEY^CSOME_VALUE^BSOME_KEY^CSOME_VALUE

The code is:

final_array = []
temp_array = []

array__with_all_of_the_data.each do |x|
  temp_array = x.split(/\^C/)
  temp_array.each do |y|
    final_array << y.split(/\^B/)
  end  
  @final_array << final_array.join(",")
end

回答1:


Split using the regular expression /\^[BC]/:

>> 'SOME_KEY^CSOME_VALUE^BSOME_KEY^CSOME_VALUE'.split(/\^[BC]/)
=> ["SOME_KEY", "SOME_VALUE", "SOME_KEY", "SOME_VALUE"]

If you want replace \B / \C with ,, use gsub instead of split + join:

>> 'SOME_KEY^CSOME_VALUE^BSOME_KEY^CSOME_VALUE'.gsub(/\^[BC]/, ',')
=> "SOME_KEY,SOME_VALUE,SOME_KEY,SOME_VALUE"


来源:https://stackoverflow.com/questions/18211617/why-cant-i-split-a-string-on-control-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!