-1

有点正则表达式新手......对不起。我有一份带有 IEEE 风格引文或括号中数字的文档。它们可以是一个数字,如 [23],或多个,如 [5, 7, 14],或一个范围,如 [12-15]。

我现在拥有的是[\[|\s|-]([0-9]{1,3})[\]|,|-].

这是捕获单个数字和组中的第一个数字,但不捕获后续数字或范围内的任何一个数字。然后我需要在表达式中引用该数字,例如\1.

我希望这很清楚!我怀疑我不理解 OR 运算符。

4

2 回答 2

1

这个怎么样?

(\[\d+\]|\[\d+-\d+\]|\[\d+(,\d+)*\])
实际上,这可以更简化为:(\[\d+-\d+\]|\[\d+(,\d+)*\])

my @test = (  
    "[5,7,14]",  
    "[23]",  
    "[12-15]"  
);  

foreach my $val (@test) {  
    if ($val =~ /(\[\d+-\d+\]|\[\d+(,\d+)*\])/ ) {  
        print "match $val!\n";  
    }  
    else {  
        print "no match!\n";  
    }  
}   

这打印:

match [5,7,14]!  
match [23]!  
match [12-15]! 

不考虑空格,但如果需要,您可以添加它们

于 2017-03-03T20:28:01.603 回答
0

我认为吉姆的回答很有帮助,但为了更好地理解,需要进行一些概括和编码:

  • 如果问题正在寻找更复杂但可能的问题,例如[1,3-5]

    (\[\d+(,\s?\d+|\d*-\d+)*\])
           ^^^^ optional space after ','
    //validates:
    [3,33-24,7]
    [3-34]
    [1,3-5]
    [1]
    [1, 2]
    

此正则表达式的演示

通过链接替换数字的 JavaScript 代码:

//define input string:
var mytext = "[3,33-24,7]\n[3-34]\n[1,3-5]\n[1]\n[1, 2]" ;

//call replace of matching [..] that calls digit replacing it-self
var newtext = mytext.replace(/(\[\d+(,\s?\d+|\d*-\d+)*\])/g ,
    function(ci){ //ci is matched citations `[..]`
        console.log(ci);
        //so replace each number in `[..]` with custom links
        return ci.replace(/\d+/g, 
            function(digit){
                return '<a href="/'+digit+'">'+digit+'</a>' ;
            });
    });
console.log(newtext);

/*output:
'[<a href="/3">3</a>,<a href="/33">33</a>-<a href="/24">24</a>,<a href="/7">7</a>]
[<a href="/3">3</a>-<a href="/34">34</a>]
[<a href="/1">1</a>,<a href="/3">3</a>-<a href="/5">5</a>]
[<a href="/1">1</a>]
[<a href="/1">1</a>, <a href="/2">2</a>]'
*/
于 2017-03-03T22:15:34.813 回答