代码重构以删除重复的正则表达式
Code refactoring to remove repetitions of regular expressions
我写了下面一段 Ruby 代码,用于从 html 页面中提取信息。
combined = state = county = special = 0
unless options.nil?
unless /([0-9\.]+)% \(Combined\)/.match(options).nil?
combined = /([0-9\.]+)% \(Combined\)/.match(options)[1].to_f
end
unless /([0-9\.]+)% \(State\)/.match(options).nil?
state = /([0-9\.]+)% \(State\)/.match(options)[1].to_f
end
unless /([0-9\.]+)% \(County\)/.match(options).nil?
county = /([0-9\.]+)% \(County\)/.match(options)[1].to_f
end
unless /([0-9\.]+)% \(Special\)/.match(options).nil?
special = /([0-9\.]+)% \(Special\)/.match(options)[1].to_f
end
if combined==0 and state==0 and county==0 and special ==0 then
unless />([0-9\.]+)%</.match(options).nil?
combined = />([0-9\.]+)%</.match(options)[1].to_f
end
end
end
我应该如何重构此代码以消除每个正则表达式的重复?
更新:相同的方法,但稍微清理了代码
results = Hash.new(0)
if options
%w(Combined State County Special).each do |query|
options =~ /([0-9\.]+)% \(#{query}\)/
results[query.downcase.intern] = .to_f if $~
end
if results.values.all?(&:zero?)
options =~ />([0-9\.]+)%</
results[:combined] = .to_f if $~
end
end
return if options.nil?
options.scan(/([0-9.]+)% \(([\w]+)\)/) do
case
when "Combined".freeze then combined = .to_f
when "State".freeze then state = .to_f
when "County".freeze then county = .to_f
when "Special".freeze then special = .to_f
else
combined = .to_f if options =~ />([0-9.]+)%</
end
end
我写了下面一段 Ruby 代码,用于从 html 页面中提取信息。
combined = state = county = special = 0
unless options.nil?
unless /([0-9\.]+)% \(Combined\)/.match(options).nil?
combined = /([0-9\.]+)% \(Combined\)/.match(options)[1].to_f
end
unless /([0-9\.]+)% \(State\)/.match(options).nil?
state = /([0-9\.]+)% \(State\)/.match(options)[1].to_f
end
unless /([0-9\.]+)% \(County\)/.match(options).nil?
county = /([0-9\.]+)% \(County\)/.match(options)[1].to_f
end
unless /([0-9\.]+)% \(Special\)/.match(options).nil?
special = /([0-9\.]+)% \(Special\)/.match(options)[1].to_f
end
if combined==0 and state==0 and county==0 and special ==0 then
unless />([0-9\.]+)%</.match(options).nil?
combined = />([0-9\.]+)%</.match(options)[1].to_f
end
end
end
我应该如何重构此代码以消除每个正则表达式的重复?
更新:相同的方法,但稍微清理了代码
results = Hash.new(0)
if options
%w(Combined State County Special).each do |query|
options =~ /([0-9\.]+)% \(#{query}\)/
results[query.downcase.intern] = .to_f if $~
end
if results.values.all?(&:zero?)
options =~ />([0-9\.]+)%</
results[:combined] = .to_f if $~
end
end
return if options.nil?
options.scan(/([0-9.]+)% \(([\w]+)\)/) do
case
when "Combined".freeze then combined = .to_f
when "State".freeze then state = .to_f
when "County".freeze then county = .to_f
when "Special".freeze then special = .to_f
else
combined = .to_f if options =~ />([0-9.]+)%</
end
end