2012-04-05 70 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)