【问题标题】:Replacing non standard characters in Ruby替换 Ruby 中的非标准字符
【发布时间】:2017-01-05 17:45:40
【问题描述】:

我有一个字符串数组:

strings = ["\u2014 some text", "\u00A0 Foo", "Bar"]

我应该写什么语句才能得到一个如下所示的数组:

strings = [" some text", " Foo", "Bar"]

我尝试了以下,但没有运气:

strings.map!{|string| string.gsub!(/(Wu2014|Wu00A0)/, '')}

【问题讨论】:

  • 您能否定义“非标准”,应保留/删除哪些字符?
  • 我想删除所有那些 Unicode 字符,如“\u2014”、“\u00A0”等。
  • 你能说得更具体点吗? “B”也是一个Unicode字符,要不要也去掉?

标签: ruby string


【解决方案1】:

你有太多的刘海和不正确的正则表达式

试一试

strings.map{|string| string.gsub!(/(\u2014|\u00A0)/, '')}

strings.map!{|string| string.gsub(/(\u2014|\u00A0)/, '')}

new_strings = strings.map{|string| string.gsub(/(\u2014|\u00A0)/, '')}
strings = new_strings

【讨论】:

  • 好吧,由于某种原因,正则表达式不返回匹配的模式......所以你的解决方案都不起作用。
【解决方案2】:

您可能希望从字符串的开头删除所有非 ASCII 字符:

strings = ["\u2014 some text", "\u00A0 Foo", "Bar"]
strings.map!{|s| s.sub(/\A\P{ASCII}+/,'')} # remove non-ASCII from the start of the string

Ruby demo

或者,您可以删除除单词和空格字符以外的所有字符

strings.map!{|s| s.sub(/\A[^\w\s]+/,'')}

this Ruby demo

详情

  • \A - 字符串开头
  • \P{ASCII} - 除 ASCII 以外的任何字符
  • [^\w\s] - 除单词 (\w) 或空格 (\s) 字符以外的任何字符
  • + - 一个量词,匹配一次或多次出现的量化模式。

【讨论】:

  • 谢谢 Wiktor,但我遇到了一个异常:Encoding::CompatibilityError: incompatible encoding regexp match (IBM437 regexp with UTF-8 string)
  • 您使用的 Ruby 版本是什么?见stackoverflow.com/questions/9857443/…
  • 很遗憾得知日期未定。
  • @CarySwoveland:你能解释一下天气下的日期是什么意思吗?
  • 如果您熟悉表达式under the weather,那应该是显而易见的。顺便说一句,该表达式的起源(在链接处向下滚动)很有趣。
【解决方案3】:

如果你想删除非 ASCII 字符,那么

strings.map{| s | s.encode('ASCII', 'binary', invalid: :replace, undef: :replace, replace: '')}

【讨论】:

  • 这将从字符串中的所有位置删除非 ASCII。我的印象是只能从字符串的开头删除。
【解决方案4】:

我建议去掉其中的刘海。如果您想删除所有非 ASCII 字符,您可以尝试:

strings.map!{|string| string.gsub(/\P{ASCII}/,'')}

这将替换所有非 ASCII 字符。对我来说,这会导致:

[" some text", " Foo", "Bar"]

【讨论】:

  • 这似乎可行,请告诉我如何匹配 UTF-8?
  • 这实际上会从字符串中删除所有非 ASCII - 这是预期的吗?
  • 我检查了字符串的编码,它返回 UTF-8
  • 我尝试了您的解决方案,但它抛出异常 Encoding::CompatibilityError: incompatible encoding regexp match (IBM437 regexp with UTF-8 string)
  • 我不知道\P(相对于\p)。很高兴知道。 /[^[[:ascii:]]]/ 也可以。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多