2012-04-05 47 views
2

这非常简单:我如何去除特殊字符的红宝石字符串?这里的字符: http://www.fileformat.info/info/unicode/char/2028/index.htm特定控制字符的地带红宝石字符串

而这里的字符串,与周期之间以及两个特殊字符结尾报价:和

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

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

" 

我失败尝试这样做使用ruby 1.9.3p125

+0

GSUB( “/ \ n /”, “”)更一般的,效率较低,在此? – Ascherer 2012-04-05 00:04:47

+0

@Ascherer不工作:( – nnyby 2012-04-05 00:05:49

+0

\ x1F^_(单元分隔符,信息分隔符之一)......去这里http://donsnotes.com/tech/charsets/ascii.html – zee 2016-01-25 05:04:44

回答

1

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

+0

我差不多发布了第一,但不知道如果红宝石可以做到这一点哈哈 – Ascherer 2012-04-05 00:19:20

+0

如果你使用的是1.8.6版本,你不能,因为它没有完全的Unicode支持。 – Matt 2012-04-05 00:24:24

6

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)