[英]Regex - match any digit in a string
我有以下Javascript
function myFunction() {
var str = "depth10 shown";
var depth= str.match(/^depth[\d+$]/);
console.log(depth);
}
我的函數試圖找出字符串中是否存在深度*,其中*始終為數字(例如:depth0,depth1,depth100)並返回其中的數值。 在上面的示例中,深度始終只返回一位而不是所有數字。 有誰能解釋為什么?
如果您不正確地使用了字符類,則需要使用捕獲組 :
var str = 'depth10 shown or depth100 and depth1'
var re = /depth(\d+)/gi,
matches = [];
while (m = re.exec(str)) {
matches.push(m[1]);
}
console.log(matches) //=> [ '10', '100', '1' ]
注意:如果字符串中有超過1個“深度*”子字符串,則需要在循環中使用exec()
方法,將捕獲組的匹配結果推送到結果數組。
否則,您可以在此處使用匹配方法:
var r = 'depth10 shown'.match(/depth(\d+)/)
if (r)
console.log(r[1]); //=> "10"
$
匹配輸入結束。 即。 /t$/
與“eater”中的't'不匹配,但在“eat”中匹配它。
^
匹配輸入的開頭。 即, /^A/
與“an A”中的“A”不匹配,但與“An E”中的“A”匹配。
嘗試:
var str = "depth10 shown".match(/depth\d+/gi);
console.log(str[0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.