Why does String.match( / \d*/ ) return an empty string?

前端 未结 4 1989
挽巷
挽巷 2020-11-27 23:34

Can someone help me to understand why using \\d* returns an array containing an empty string, whereas using \\d+ returns [\"100\"] (as expected). I get why the \\d+ works, b

4条回答
  •  粉色の甜心
    2020-11-28 00:13

    /\d*/

    means "match against 0 or more numbers starting from the beginning of the string".

    When you start the beginning for your string, it immediately hits a non-number and can't go any further. Yet this is considered a successful match because "0 or more".

    You can try either "1 or more" via

    /\d+/
    

    or you can tell it to match "0 or more" from the end of the string:

    /\d*$/
    

    Find all in Python

    In Python, there is the findall() method which returns all parts of the string your regular expression matched against.

    re.findall(r'\d*', 'one to 100')
    # => ['', '', '', '', '', '', '', '100', '']
    

    .match() in JavaScript, returns only the first match, which would be the first element in the above array.

提交回复
热议问题