正则表达式仅匹配 RAR 文件集中的第一个文件 [英] Regular expression to match only the first file in a RAR file set

查看:63
本文介绍了正则表达式仅匹配 RAR 文件集中的第一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要查看在哪个文件上调用 unrar 命令,需要确定哪个文件是文件集中的第一个.

以下是一些示例文件名,其中 - 自然 - 只应匹配第一组:

yes.rar是的.part1.rar是的.part01.rar是的.part001.rar编号.part2.rar编号part02.rar编号part002.rar编号part011.rar

使用与 PCRE 兼容的正则表达式的一种(有限)方法是:

.*(?:(?

然而,当我在 Rejax 上测试时,这在 Ruby 中不起作用.>

您将如何编写一个 Ruby 兼容正则表达式以仅匹配一组 RAR 文件中的第一个文件?

解决方案

简短的回答是,无法构建单个正则表达式来满足您的问题.Ruby 1.8 没有环视断言(您的示例正则表达式中的 (?<! 内容),这就是您的正则表达式不起作用的原因.这给您留下了两个选择.

1) 使用多个正则表达式来做到这一点.

def is_first_rar(文件名)if ((文件名 =~/part(\d+)\.rar$/) == nil)return (filename =~/\.rar$/) != nil别的返回 $1.to_i == 1结尾结尾

2) 使用 ruby​​ 1.9 的正则表达式引擎,Oniguruma.它支持环视断言,您可以将其安装为 ruby​​ 1.8 的 gem.之后,您可以执行以下操作:

def is_first_rar(文件名)reg = Oniguruma::ORegexp.new('.*(?:(?

To see what file to invoke the unrar command on, one needs to determine which file is the first in the file set.

Here are some sample file names, of which - naturally - only the first group should be matched:

yes.rar
yes.part1.rar
yes.part01.rar
yes.part001.rar

no.part2.rar
no.part02.rar
no.part002.rar
no.part011.rar

One (limited) way to do it with PCRE compatible regexps is this:

.*(?:(?<!part\d\d\d|part\d\d|\d)\.rar|\.part0*1\.rar)

This did not work in Ruby when I tested it at Rejax however.

How would you write one Ruby compatible regular expression to match only the first file in a set of RAR files?

解决方案

The short answer is that it's not possible to construct a single regex to satisfy your problem. Ruby 1.8 does not have lookaround assertions (the (?<! stuff in your example regex) which is why your regex doesn't work. This leaves you with two options.

1) Use more than one regex to do it.

def is_first_rar(filename)
    if ((filename =~ /part(\d+)\.rar$/) == nil)
        return (filename =~ /\.rar$/) != nil
    else
        return $1.to_i == 1
    end
end

2) Use the regex engine for ruby 1.9, Oniguruma. It supports lookaround assertions, and you can install it as a gem for ruby 1.8. After that, you can do something like this:

def is_first_rar(filename)
    reg = Oniguruma::ORegexp.new('.*(?:(?<!part\d\d\d|part\d\d|\d)\.rar|\.part0*1\.rar)')
    match = reg.match(filename)
    return match != nil
end

这篇关于正则表达式仅匹配 RAR 文件集中的第一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆