【问题标题】:Regex - match any digit in a string正则表达式 - 匹配字符串中的任何数字
【发布时间】:2015-06-10 03:40:57
【问题描述】:

我有以下 Javascript

function myFunction() {
    var str = "depth10 shown"; 
    var depth= str.match(/^depth[\d+$]/);
    console.log(depth);
}

我的函数正在尝试查找字符串中是否存在 depth*,其中 * 始终为数字(例如:depth0、depth1、depth100)并返回其中的数字值。在上面的例子中,depth 总是只返回一个数字而不是所有数字。谁能解释一下为什么?

【问题讨论】:

  • [\d+$] 将匹配一个数字或加号或$
  • debuggex 粘贴您的正则表达式 - 减去斜线 - 它会直观地向您显示您在此处发布的内容的“之一”条件。然后将其与网站上的其他两个比较:^depth\d+$^depth(\d+)$ 忽略 ^$ 锚,看看它们有何不同。

标签: javascript regex


【解决方案1】:

您不正确地使用了字符类,您想改用capturing group

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"

【讨论】:

  • 如果有多个“深度*”子字符串,我怎样才能始终返回第一个?可能是matches[0]?
【解决方案2】:

$ 匹配输入的结尾。 IE。 /t$/ 与 "eater" 中的 't' 不匹配,但在 "eat" 中匹配。

^ 匹配输入的开头。即,/^A/ 不匹配“an A”中的“A”,但匹配“An E”中的“A”。

试试:

var str = "depth10 shown".match(/depth\d+/gi);
console.log(str[0])

【讨论】:

    猜你喜欢
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 2012-06-05
    • 2013-12-25
    相关资源
    最近更新 更多