134 "ange134".match(/\d*/) // result => "" //expected 13...">

* and + behavior differently in regular expression

"ange134".match(/\d+/)       // result =>  134
"ange134".match(/\d*/)       // result =>  ""     //expected 134

In the above cases, +behaves well, being greedy.

But why /\d*/doesn't it return the same thing?

+4
source share
3 answers
"ange134".match(/\d+/)       // result =>  123

In the above case, \d+make sure that there is at least one digit that can be followed by more, so when the scan starts and it finds “a” at the beginning, it still continues to search for numbers as the condition is not fulfilled.

"ange134".match(/\d*/)       // result =>  ""     //expected 123

\d* , . , "a", (, )... .

/g, . . , , . , .

console.log("ange134".match(/\d*/));
console.log("ange134".match(/\d*$/));
console.log("ange134".match(/\d*/g));
console.log("134ange".match(/\d*/));   // this will return 134 as that is the first match that it gets
Hide result
+6
"ange134".match(/\d*/);

" 0 ". , . :

"ange134".match(/\d*$/);

, - - , , 134 .

0
"ange134".match(/\d*/) //means 0 or more times, and this match in the first
//letter (because it "returns false") because you aren't using global flag that search in the whole string

if you want it to work, use the global flag:

"ange134".match(/\d*/g)

or use your first correct option without a flag:

"ange134".match(/\d+/)

this link has an explanation of why it matches the first letter "a": https://regex101.com/r/3ItllY/1/

0
source

Source: https://habr.com/ru/post/1687102/


All Articles