我有一个我想要转换的示例字符串,从中:
#21inch-#25inch
到此:
#21inch #22inch #23inch #24inch #25inch
使用Ruby,请告诉我如何做到这一点。
答案 0 :(得分:6)
你可以scan
你的字符串并使用字符串范围:
numbers = "#21inch-#25inch".scan(/\d+/)
=> ["21", "25"]
Range.new(*numbers).map{ |s| "##{s}inch" }.join(" ")
=> "#21inch #22inch #23inch #24inch #25inch"
此解决方案仅在您的字符串具有类似实例的格式时才起作用。对于其他情况,您应该编写自己的特定解决方案。
答案 1 :(得分:4)
R = /
(\D*) # match zero or more non-digits in capture group 1
(\d+) # match one or more digits in capture group 2
([^\d-]+) # match on or more chars other the digits and hyphens in capture group 3
/x # free-spacing regex definition mode
def spin_out(str)
(prefix, first, units),(_, last, _) = str.scan(R)
(first..last).map { |s| "%s%s%s" % [prefix,s,units] }.join(' ')
end
spin_out "#21inch-#25inch"
#=> "#21inch #22inch #23inch #24inch #25inch"
spin_out "#45cm-#53cm"
#=> "#45cm #46cm #47cm #48cm #49cm #50cm #51cm #52cm #53cm"
spin_out "sz 45cm-sz 53cm"
#=> "sz 45cm sz 46cm sz 47cm sz 48cm sz 49cm sz 50cm sz 51cm sz 52cm sz 53cm"
spin_out "45cm-53cm"
#=> "45cm 46cm 47cm 48cm 49cm 50cm 51cm 52cm 53cm"
对于str = "#21inch-#25inch"
,我们获得
(prefix, first, units),(_, last, _) = str.scan(R)
#=> [["#", "21", "inch"], ["-#", "25", "inch"]]
prefix
#=> "#"
first
#=> "21"
units
#=> "inch"
last
#=> "25"
后续的映射非常简单。
答案 2 :(得分:2)
您可以使用带有匹配替换的正则表达式gsub,如下所示:
string = "#21inch-#25inch"
new_string = string.gsub(/#\d+\w+-#\d+\w+/) do |match|
first_capture, last_capture = match.split("-")
first_num = first_capture.gsub(/\D+/, "").to_i
last_num = last_capture.gsub(/\D+/, "").to_i
pattern = first_capture.split(/\d+/)
(first_num..last_num).map {|num| pattern.join(num.to_s) }.join(" ")
end
puts "#{new_string}"
运行此命令将产生此输出:
First: #21inch Last: #25inch
First num: 21 Last num: 25
Pattern: ["#", "inch"]
#21inch #22inch #23inch #24inch #25inch
输出的最后一行是答案,前面的行显示了到达那里的逻辑进展。
此方法也适用于其他略有不同的单位格式:
#32ft-#49ft
#1mm-5mm
#2acres-5acres
使这个适合多种用途将非常简单。如果正则表达式略有不同,您还可以支持范围格式#21inch..#25inch
:
/(#\d+\w+)[-.]+(#\d+\w+)/
快乐解析!