Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby Regexp在pry、rubular中匹配和捕获,但不是从脚本中_Ruby_Regex - Fatal编程技术网

Ruby Regexp在pry、rubular中匹配和捕获,但不是从脚本中

Ruby Regexp在pry、rubular中匹配和捕获,但不是从脚本中,ruby,regex,Ruby,Regex,因此,我有一个regexp,我已经在Rubular和CLI上进行了测试(使用prygem)。这将解析定制的Apache日志格式。当我在pry中将输入输入输入到它时,它会按预期工作(例如,$~已填充)。Rubular还报告不同输入行的正确匹配和分组。从下面的代码运行时,没有匹配项 我也尝试过使用String.chomp和\n字符,以防失去匹配,但各种排列都没有效果 我相信这是一个更有经验的红宝石家可以解释的 红细胞连接: 以下是相关的代码、正则表达式和输入——请提前感谢: log_regex =

因此,我有一个regexp,我已经在Rubular和CLI上进行了测试(使用
pry
gem)。这将解析定制的Apache日志格式。当我在pry中将输入输入输入到它时,它会按预期工作(例如,
$~
已填充)。Rubular还报告不同输入行的正确匹配和分组。从下面的代码运行时,没有匹配项

我也尝试过使用
String.chomp
\n
字符,以防失去匹配,但各种排列都没有效果

我相信这是一个更有经验的红宝石家可以解释的

红细胞连接:

以下是相关的代码、正则表达式和输入——请提前感谢:

log_regex = %r{
            (?<ip>(([0-9]{1,3}\.){3}[0-9]{1,3}))                                                                   
            \s-\s
            (?<src_ip>.*)
            -\s
            (?<date>\[.*\])
            \s
            (?<url>".+")
            \s
            (?<response>\d{3})
            \s
            (?<length>\d+)
            \s
            (?<referer>".+")
            \s
            (?<useragent>".*")
            \s(?<host>.*)?
            /ix
            }

logfile = ARGV[0]

def process_log(log_regex,logfile)
    IO.foreach(logfile, 'r') do |line|
        line.chomp!
        log_regex.match(line) do |m|
            puts m['ip']
        end
    end
end

process_log(log_regex,logfile)

您可能想仔细看看正则表达式的定义。您的标志位于模式定义内,而不是在它们所属的
%r
关闭后:

%r{
...
/ix
}
应该是:

%r{
...
}ix
来自IRB:

irb(main):001:0> %r{foo/ix}
/foo\/ix/
irb(main):002:0> %r{foo}ix
/foo/ix
irb(main):003:0> %r{^foo$}ix =~ 'foo'
0
irb(main):004:0> %r{^foo/ix$} =~ 'foo'
nil

对于上述测试,PRY和IRB都返回相同的结果。

我巧妙地将
ix
放在PRY的适当位置,但没有放在脚本中。由于使用了(相对)复杂的regexp,而且由于我来自另一种语言,所以完全没有人注意到它。谢谢你,好心的先生!
irb(main):001:0> %r{foo/ix}
/foo\/ix/
irb(main):002:0> %r{foo}ix
/foo/ix
irb(main):003:0> %r{^foo$}ix =~ 'foo'
0
irb(main):004:0> %r{^foo/ix$} =~ 'foo'
nil