正则表达式匹配单个页面或页面范围?

AJ.*_*AJ. 2 regex

嘿伙计.我正在努力使用与"单页/页面范围"文本框中的输入匹配的正则表达式,这意味着用户可以以[lowerBound] - [upperBound]格式输入单个整数或整数范围.例如:


  • 11:比赛
  • 2:匹配
  • 2-9:匹配
  • 2a:不匹配
  • 19-:不匹配

一个正则表达式可以实现吗?

奖金

  • 9-2:不匹配

提前致谢.

eph*_*ent 9

正如布莱恩所说,比较两个数字并不是正则表达式的目的.如果您想检查奖金案例,您应该在正则表达式之外.

/^(\d+)(?:-(\d+))?$/ && $1 < $2;
Run Code Online (Sandbox Code Playgroud)

话虽这么说,大多数"正则表达式"引擎实际上并不是常规的,所以(例如)它可能在Perl 5中:

m{                     # /../ is shorthand for m/../
    \A                 # beginning of string
    (\d+)              # first number
    (?:-               # a non-capturing group starting with '-'...
        (\d+)          #     second number
        (?(?{$1>=$2})  #     if first number is >= second number
            (?!))      #         fail this match
    )?                 # ...this group is optional
    \Z                 # end of string
}x                     # /x tells Perl to allow spaces and comments inside regex
Run Code Online (Sandbox Code Playgroud)

或者/^(\d+)(?:-(\d+)(?:(?{$1>=$2})(?!)))?$/简而言之.在Perl 5.6.1,5.8.8和5.10.0中测试.


为了匹配范围的扩展定义建议,

/^\s*
    (\d+) (?:\s*-\s* (\d+))?
    (?:\s*,\s* (\d+) (?:\s*-\s* (\d+))?)*
\s*$/x
Run Code Online (Sandbox Code Playgroud)

使用一些Perl 5.10功能,甚至可以确保数字排序良好:

m{
    \A\s*                              # start of string, spaces
    (?{{$min = 0}})                    # initialize min := 0
    (?&RANGE) (?:\s*,\s* (?&RANGE))*   # a range, many (comma, range)
    \s*\Z                              # spaces, end of string

    (?(DEFINE)                         # define the named groups:
        (?<NUMBER>                     #   number :=
            (\d*)                      #     a sequence of digits
            (?(?{$min < $^N})          #     if this number is greater than min
                (?{{$min = $^N}})      #       then update min
                | (?!)))               #       else fail
        (?<RANGE>                      #   range :=
            (?&NUMBER)                 #     a number
            (?:\s*-\s* (?&NUMBER))?))  #     maybe a hyphen and another number
}x
Run Code Online (Sandbox Code Playgroud)