【发布时间】:2013-03-31 00:29:36
【问题描述】:
假设我有一个字符串如下:
"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) 并使用相同的正则表达式时,我得到了所需的哈希值。为什么这种方法不是这样?
【问题讨论】:
-
如果设置为
strip[0]会怎样? -
@Linuxios 如果我这样做,它将返回原始字符串,
1是MatchData数组中的第二项。该项目是正则表达式匹配的原因。