去除特定控制字符的 ruby​​ 字符串

2024-03-18

这非常简单:如何去除 ruby​​ 字符串中的特殊字符?这是角色:http://www.fileformat.info/info/unicode/char/2028/index.htm 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]/, '')

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

我正在使用红宝石 1.9.3p125


String#gsub会起作用,但比这更通用且效率更低字符串#tr http://ruby-doc.org/core-1.9.3/String.html#method-i-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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

去除特定控制字符的 ruby​​ 字符串 的相关文章

随机推荐