Regex that can match empty string is breaking the javascript regex engine

前端 未结 2 1260
暗喜
暗喜 2020-11-27 08:29

I wrote the following regex: /\\D(?!.*\\D)|^-?|\\d+/g

I think it should work this way:

\\D(?!.*\\D)    # match the last non-digit
|              


        
2条回答
  •  渐次进展
    2020-11-27 09:24

    You can reorder your alternation patterns and use this in JS to make it work:

    var arrTest = '12,345,678.90'.match(/\D(?!.*\D)|\d+|^-?/g);
    console.log(arrTest);
    
    var test = arrTest.join('').replace(/\D/, '.');
    
    console.log(test);
    
    //=> 12345678.90

    RegEx Demo

    This is the difference between Javascript and PHP(PCRE) regex behavior.

    In Javascript:

    '12345'.match(/^|.+/gm)
    //=> ["", "2345"]
    

    In PHP:

    preg_match_all('/^|.+/m', '12345', $m);
    print_r($m);
    Array
    (
        [0] => Array
            (
                [0] =>
                [1] => 12345
            )
        )
    

    So when you match ^ in Javascript, regex engine moves one position ahead and anything after alternation | matches from 2nd position omwards in input.

提交回复
热议问题