【问题标题】:Strip ruby string of a specific control character剥离特定控制字符的 ruby​​ 字符串
【发布时间】:2012-04-05 00:02:21
【问题描述】:

这很简单:如何去掉一个特殊字符的 ruby​​ 字符串?这是角色: http://www.fileformat.info/info/unicode/char/2028/index.htm

这是字符串,在句点和结束引号之间有两个特殊字符:

"Each of the levels requires logic, skill, and brute force to crush the enemy.

"

我试过这个没有成功:

string.gsub!(/[\x00-\x1F\x7F]/, '')

gsub("/\n/", "")

我正在使用 ruby​​ 1.9.3p125

【问题讨论】:

标签: ruby


【解决方案1】:

String#gsub 可以,但比String#tr 更通用,效率更低

irb> s ="Hello,\u2028 World; here's some ctrl [\1\2\3\4\5\6] chars"
=> "Hello,\u2028 World; here's some ctrl [\u0001\u0002\u0003\u0004\u0005\u0006] chars"

irb> s.tr("\u0000-\u001f\u007f\u2028",'')
=> "Hello, World; here's some ctrl [] chars"

require 'benchmark'
Benchmark.bm {|x|
  x.report('tr')   { 1_000_000.times{ s.tr("\u0000-\u001f\u007f\u2028",'') } }
  x.report('gsub') { 1_000_000.times{ s.gsub(/[\0-\x1f\x7f\u2028]/,'') } }
}

          user     system      total        real
tr    1.440000   0.000000   1.440000 (  1.448090)
gsub  4.110000   0.000000   4.110000 (  4.127100)

【讨论】:

    【解决方案2】:

    我想通了! .gsub(/\u2028/, '')

    【讨论】:

    • 我差点先发了,但不知道 ruby​​ 能不能做到哈哈
    • 如果您使用的是 1.8.6 版本,则不能,因为它没有完整的 Unicode 支持。
    猜你喜欢
    • 2011-11-16
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2010-09-19
    • 2012-09-30
    相关资源
    最近更新 更多