需要正则表达式来捕获编号引用

时间:2017-03-03 20:09:36

标签: regex citations

一个正则表达式的新手...抱歉。我有一个IEEE样式引用的文档,或括号中的数字。它们可以是一个数字,如[23],或几个,如[5,7,14]或范围,如[12-15]。

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

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

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

2 个答案:

答案 0 :(得分: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]! 

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

答案 1 :(得分:0)

我认为Jim的答案很有帮助,但有些概括和编码可以更好地理解:

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

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

Demo for this Regex

通过链接替换数字的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>]'
*/