0

我需要一个最佳的正则表达式来匹配文本文件中的所有这三种类型的文本。

  1. [真假]
  2. [4,5,6,7]
  3. [2-15]

我正在尝试以下不起作用的正则表达式匹配

m/([0-9A-Fa-fx,]+)\s*[-~,]\s*([0-9A-Fa-fx,]+)/) 
4

3 回答 3

3
/
   (?(DEFINE)
      (?<WORD> [a-zA-Z]+ )
      (?<NUM>  [0-9]+ )
   )

   \[ \s*
   (?: (?&WORD) (?: \s* , \s* (?&WORD) )+
   |   (?&NUM) (?: \s* , \s* (?&NUM) )+
   |   (?&NUM) \s* - \s* (?&NUM)
   )
   \s* \]
/x
于 2013-03-01T12:47:14.867 回答
2

4-7是 的子集2-15。此正则表达式应捕获它们:

/TRUE|FALSE|[2-9]|1[0-5]/
于 2013-03-01T12:30:30.780 回答
0

一个quick'n'dirty测试程序:

#!/usr/bin/env perl

use strict;
use warnings;

for my $line (<DATA>) {

    chomp $line;
    print "$line: ";

    if ($line =~ /
            ^                                   # beginning of the string
            \[                                  # a literal opening sq. bracket
            (                                   # alternatives:
                  (TRUE|FALSE) (,(TRUE|FALSE))*     # one or more thruth words
                | (\d+) (,\d+)*                     # one or more numbers
                | (\d+) - (\d+)                     # a range of numbers
            )                                   # end of alternatives
            \]                                  # a literal closing sq. bracket
            $                                   # end of the string
        /x) {

        print "match\n";
    }
    else {
        print "no match\n";
    }
}

__DATA__
[TRUE]
foo
[FALSE,TRUE,FALSE]
[FALSE,TRUE,]
[42,FALSE]
[17,42,666]
bar
[17-42]
[17,42-666]

输出:

[TRUE]: match
foo: no match
[FALSE,TRUE,FALSE]: match
[FALSE,TRUE,]: no match
[42,FALSE]: no match
[17,42,666]: match
bar: no match
[17-42]: match
[17,42-666]: no match
于 2013-03-01T15:22:45.683 回答