" 2013 " -6ren">
gpt4 book ai didi

Ruby 去除空格?

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:38 24 4
gpt4 key购买 nike

在删除   空格时遇到一些问题。

vehicle = [" 2013 ", "BMW ", "535 ", "Sedan 4 Door "] 
v = vehicle[0]
# => " 2013 "

v[-1].ord.chr
# => "\xA0"

失败的尝试:

vehicle.map { |d| d.gsub(/\S(\w*)/, '\1') }
# => ["2013", "MW", "35", "edan oor"] (space gone but so are other characters.)

vehicle.map { |d| d.gsub(/\xA0/, '') }
# => SyntaxError: (irb):340: invalid multibyte escape: /\xA0/

vehicle.map { |d| d.gsub(/#{160.chr}/, '') }
# => Encoding::CompatibilityError: incompatible encoding regexp match (ASCII-8BIT regexp with UTF-8 string)

来自 this question 的回答作品:

vehicle.map { |d| d.gsub("\302\240", ' ').strip }
# => ["2013", "BMW", "535", "Sedan 4 Door"]

但它没有解释为什么/如何。有人可以解释这是如何以及为什么有效的吗?或者建议替代方案?

最佳答案

应该可能能够简单地使用 /[[:space:]]/ 来匹配所有空格 ( unicode or not )。

\302\240 只是 utf8 编码的 nbsp 表示。

关于Ruby 去除空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23553828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com