我不知道这是怎么做的,因为我对正则表达式很陌生,似乎找不到合适的方法来完成这个但是说我有以下作为字符串(包括所有标签和新行)
1/2 cup
onion
(chopped)
Run Code Online (Sandbox Code Playgroud)
如何删除所有空格并用一个空格替换每个实例?
Chu*_*uck 61
这是正则表达式运行良好的情况,因为您希望将整个类的空白字符视为相同,并用空格字符替换任何空白组合的运行.因此,如果存储了该字符串s,那么您将执行以下操作:
fixed_string = s.gsub(/\s+/, ' ')
Run Code Online (Sandbox Code Playgroud)
ssc*_*eck 18
在Rails中你可以使用String#squish,这是一个active_support扩展.
require 'active_support'
s = <<-EOS
1/2 cup
onion
EOS
s.squish
# => 1/2 cup onion
Run Code Online (Sandbox Code Playgroud)
你想要挤压方法:
str.squeeze([other_str]*) ? new_str
Builds a set of characters from the other_str parameter(s) using the procedure described for String#count. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character.
"yellow moon".squeeze #=> "yelow mon"
" now is the".squeeze(" ") #=> " now is the"
"putters shoot balls".squeeze("m-z") #=> "puters shot balls"
Run Code Online (Sandbox Code Playgroud)
最简单的解决方案的问题gsub(/\s+/, ' ')在于它非常缓慢,因为它取代了每个空间,即使它是单个空间.但通常在单词之间有1个空格,我们应该只在序列中有2个或更多的空格时才能修复.
更好的解决方案是gsub(/[\r\n\t]/, ' ').gsub(/ {2,}/, ' ')- 首先摆脱特殊的空白,然后挤压正常的空间
def method1(s) s.gsub!(/\s+/, ' '); s end
def method2(s) s.gsub!(/[\r\n\t]/, ' '); s.gsub!(/ {2,}/, ' '); s end
Benchmark.bm do |x|
n = 100_000
x.report('method1') { n.times { method1("Lorem ipsum\n\n dolor \t\t\tsit amet, consectetur\n \n\t\n adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } }
x.report('method2') { n.times { method2("Lorem ipsum\n\n dolor \t\t\tsit amet, consectetur\n \n\t\n adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } }
end;1
# user system total real
# method1 4.090000 0.010000 4.100000 ( 4.124844)
# method2 1.590000 0.010000 1.600000 ( 1.611443)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11814 次 |
| 最近记录: |