I was just looking for a regex that would watch the last numerical (\\d or [0-9]) in a given string , strings like:
var str = "7-Dec-1985"
var str = "#scrollto-section-4"
Of-course I found an answer in the following thread on SO HERE
I am using a regex like the following:
str.match(/\d+$/)
Works fine, no issues, now I used the following tool to analysis the regex HERE ,
\d+ //matches greedy 0 to as many
$ - specifies that the search should start at the end of the string
But why does that above regex in the below example:
var str = "7-Dec-1985"
Match only 1985
why not 71985
?
Because $
means "end of input" (or "end of line or end of input" if you specify the m
flag), and \\d+
means a contiguous series of digits (not digits mixed with other things). So \\d+$
means "a contiguous series of digits right before the end."
If you want to match anywhere, remove the $
. Additionally, if you want to match more than once, you'll need a g
("global") flag on it.
Examples -- your original:
var str = "7-Dec-1985"; document.body.innerHTML = JSON.stringify(str.match(/\\d+$/));
Without the $
, but no g
:
var str = "7-Dec-1985"; document.body.innerHTML = JSON.stringify(str.match(/\\d+/));
Without the $
and with g
:
var str = "7-Dec-1985"; document.body.innerHTML = JSON.stringify(str.match(/\\d+/g));
Sorry, but $
doesn't means start search at end of string.
Your regex \\d+$
means match the number at end of string .
To match any number use \\d+
like this .
Because there is -Dec-
between 7
and 1985
which isn't digit. Also $
means end of line. So Your pattern just matches that number which is end of string (continuously) .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.