[英]Regex - match any digit in a string
I have the following Javascript 我有以下Javascript
function myFunction() {
var str = "depth10 shown";
var depth= str.match(/^depth[\d+$]/);
console.log(depth);
}
My function is trying to find if depth* is present in the string, where * is always numeric (ex: depth0, depth1, depth100) and return the numeric value in it. 我的函数试图找出字符串中是否存在深度*,其中*始终为数字(例如:depth0,depth1,depth100)并返回其中的数值。 In the example above, depth is always returning only one digit instead of all digits.
在上面的示例中,深度始终只返回一位而不是所有数字。 Can anyone explain why?
有谁能解释为什么?
You're improperly utilizing a character class, you want to use a capturing group instead: 如果您不正确地使用了字符类,则需要使用捕获组 :
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' ]
Note: If you will have more than 1 "depth*" substrings in your string, you'll want to use the exec()
method in a loop pushing the match result of the captured group to the results array. 注意:如果字符串中有超过1个“深度*”子字符串,则需要在循环中使用
exec()
方法,将捕获组的匹配结果推送到结果数组。
Otherwise, you can use the match method here: 否则,您可以在此处使用匹配方法:
var r = 'depth10 shown'.match(/depth(\d+)/)
if (r)
console.log(r[1]); //=> "10"
$
Matches end of input. $
匹配输入结束。 ie. 即。
/t$/
does not match the 't' in "eater", but does match it in "eat". /t$/
与“eater”中的't'不匹配,但在“eat”中匹配它。
^
Matches beginning of input. ^
匹配输入的开头。 ie, /^A/
does not match the 'A' in "an A", but does match the 'A' in "An E". 即,
/^A/
与“an A”中的“A”不匹配,但与“An E”中的“A”匹配。
Try: 尝试:
var str = "depth10 shown".match(/depth\d+/gi);
console.log(str[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.