2013-03-30 53 views
0

说我有一个字符串,如下所示:为什么这个正则表达式返回不正确的值?

"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

如果你把它设置为'条[0]'? – Linuxios

+0

@Linuxios如果我这样做了,它会返回原始字符串,'1'是MatchData数组中的第二项。这个项目是正则表达式匹配的原因。 – raf

回答

2

使用non-greedy repetition代替:

/#{arg}:\s(.*?);/ 
+0

工作很好!你认为我应该在逐行解析中使用它吗? [源代码](https://raw.github.com/RafalChmiel/configurer/master/configurer.rb)。 – raf

+0

它应该没有区别 - 只要该值不包含分号。也许你应该在那里使用它,只是为了有人把它复制到一个地方,它应该匹配多个键 - 值对...... – Bergi

+0

好的,谢谢,我会研究一下。 – raf

相关问题