[英]Why does't regex match all numbers instead of numbers just at the end of the string?
我只是在尋找一個正則表達式,它將監視給定字符串中的最后一個數字(\\ d或[0-9]),例如:
var str = "7-Dec-1985"
var str = "#scrollto-section-4"
的,當然,我發現了以下螺紋的答案上的SO 這里
我正在使用如下正則表達式:
str.match(/\d+$/)
工作正常,沒有問題,現在我使用以下工具來分析regex 這里 ,
\d+ //matches greedy 0 to as many
$ - specifies that the search should start at the end of the string
但是,為什么在下面的示例中在正則表達式上方執行以下操作:
var str = "7-Dec-1985"
僅匹配1985
何樂而不為71985
?
因為$
表示“輸入的結尾”(如果指定了m
標志,則表示“行的結尾或輸入的結尾”),而\\d+
表示連續的數字序列(不是與其他事物混合的數字)。 因此\\d+$
意思是“結尾處連續的一系列數字”。
如果要在任何地方匹配,請刪除$
。 另外,如果您要匹配多個,則需要在其上帶有g
(“全局”)標志。
示例-您的原始照片:
var str = "7-Dec-1985"; document.body.innerHTML = JSON.stringify(str.match(/\\d+$/));
沒有$
,但是沒有g
:
var str = "7-Dec-1985"; document.body.innerHTML = JSON.stringify(str.match(/\\d+/));
不帶$
且帶g
:
var str = "7-Dec-1985"; document.body.innerHTML = JSON.stringify(str.match(/\\d+/g));
因為在7
到1985
之間有-Dec-
而不是數字。 $
表示行尾。 因此,您的模式僅與字符串結尾的數字匹配(連續) 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.