说我有一个字符串,如下所示:为什么这个正则表达式返回不正确的值?
"auto: true; server: false;"
...我想正则表达式来创建这些设置的哈希值。我有下面的代码:
# class Configurer...
def spit(path = "", *args)
spat = Hash.new
if File.file?(path)
# Parse file
else
args.each do |arg|
begin
if path.include? arg + ":"
strip = path.match(/#{arg}:\s(.*);/)
spat[arg] = strip[1]
end
rescue
return "Error when parsing '#{arg}' in direct input."
end
end
end
spat
end
当这样的:
config = Configurer.new
puts config.spit("auto: true; server: false;", "auto", "server")
...是跑,输出的不正确的哈希:
# => {"auto"=>"true; server: false", "server"=>"false"}
这是为什么?当我parse a file (line by line)并使用相同的正则表达式我得到所需的散列。为什么这种方法不是这种情况?
如果你把它设置为'条[0]'? – Linuxios
@Linuxios如果我这样做了,它会返回原始字符串,'1'是MatchData数组中的第二项。这个项目是正则表达式匹配的原因。 – raf