[英]Why does't regex match all numbers instead of numbers just at the end of the string?
I was just looking for a regex that would watch the last numerical (\\d or [0-9]) in a given string , strings like: 我只是在寻找一个正则表达式,它将监视给定字符串中的最后一个数字(\\ d或[0-9]),例如:
var str = "7-Dec-1985"
var str = "#scrollto-section-4"
Of-course I found an answer in the following thread on SO HERE 的,当然,我发现了以下螺纹的答案上的SO 这里
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 , 工作正常,没有问题,现在我使用以下工具来分析regex 这里 ,
\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
? 仅匹配1985
何乐而不为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). 因为$
表示“输入的结尾”(如果指定了m
标志,则表示“行的结尾或输入的结尾”),而\\d+
表示连续的数字序列(不是与其他事物混合的数字)。 So \\d+$
means "a contiguous series of digits right before the end." 因此\\d+$
意思是“结尾处连续的一系列数字”。
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. 另外,如果您要匹配多个,则需要在其上带有g
(“全局”)标志。
Examples -- your original: 示例-您的原始照片:
var str = "7-Dec-1985"; document.body.innerHTML = JSON.stringify(str.match(/\\d+$/));
Without the $
, but no g
: 没有$
,但是没有g
:
var str = "7-Dec-1985"; document.body.innerHTML = JSON.stringify(str.match(/\\d+/));
Without the $
and with g
: 不带$
且带g
:
var str = "7-Dec-1985"; document.body.innerHTML = JSON.stringify(str.match(/\\d+/g));
Because there is -Dec-
between 7
and 1985
which isn't digit. 因为在7
到1985
之间有-Dec-
而不是数字。 Also $
means end of line. $
表示行尾。 So Your pattern just matches that number which is end of string (continuously) . 因此,您的模式仅与字符串结尾的数字匹配(连续) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.