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

Can someone help me understand why using \ d * returns an array containing an empty string, while using \ d + returns ["100"] (as expected). I understand why \ d + works, but I don’t understand why \ d * does not work. Does this use * to return a zero-length match and how exactly does it work?

var str = 'one to 100'; var regex = /\d*/; console.log(str.match(regex)); // [""] 
+5
source share
4 answers

Remember that match searches for the first substring that it can find that matches the given regular expression.

* means that there may be zero or more of something, so \d* means you are looking for a string containing zero or more digits.

If your input line starts with a number, that integer will match.

 "5 to 100".match(/\d*/); // "5" "5 to 100".match(/\d+/); // "5" 

But since the first character is not a digit, match() indicates that the beginning of the line (without characters) matches the regular expression.

Since your line does not start with any digits, an empty line is the first substring of your input that matches this regular expression.

+8
source

/\d*/

means "match 0 or more numbers starting at the beginning of a line."

When you start to start your line, it immediately gets into a non-number and cannot go any further. However, this is considered successful because "0 or more."

You can try "1 or more" through

 /\d+/ 

or you can say that it matches "0 or more" from the end of the line:

 /\d*$/ 

Find everything in Python

In Python, there is a findall() method that returns all parts of the string to which your regular expression matches.

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

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

+3
source

* means 0 or more, so it matches 0 times. You need to use + for 1 or more. By default, it is greedy, so it will match 100 :

 var str = 'one to 100'; var regex = /\d+/; console.log(str.match(regex)); // ["100"] 
+2
source

As @StriplingWarrior below shows, an empty string is the first match, so it returns. I would like to add that you can say what matches the regular expression by noticing the "index" field returned by the match function. For example, this is what I get when I run your code in Chrome:

 ["", index: 0, input: "one to 100"] 
+1
source

All Articles