[英]JavaScript regular expression using character class with quantifier
我有:
var regex = /[\d]*/;
var str = 'tom123is456';
var match = str.match( regex );
document.write(match);
我本以期待回到123456。
根據我的理解,問號(*)告訴引擎匹配0或更多事物的出現,加號(+)告訴引擎匹配一個或多個出現的東西。 現在“\\ d”是0-9的縮寫。
在上面的例子中,我什么都沒有回來。 當我使用加號(+)時,我會回來123.任何人都可以解釋為什么會這樣嗎?
你不應該混淆全局搜索而不是 / *一個*和更多匹配因此。 如果需要匹配字符串中的所有數字,請使用global g
flag:
'tom123is456'.match(/\d/g); // ["1", "2", "3", "4", "5", "6"]
要獲得后續令牌匹配,請使用*
或+
:
'tom123is456'.match(/\d+/g); // ["123", "456"]
參考: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_Searching_With_Flags
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.