【问题标题】:Javascript Regex to Extract a NumberJavascript 正则表达式提取数字
【发布时间】:2015-06-14 16:25:44
【问题描述】:

我有诸如

之类的字符串
(123)abc
defg(456)
hijkl
(999)
7

我想用正则表达式一次匹配这些字符串,以从字符串中提取任何数字.因此,在上面的 5 个示例中,第一种情况下我会匹配 123,第二种和第三种情况下不匹配,第四种情况下匹配 999,第五种情况下不匹配。

我试过了

var regex = new RegExp("^\((\d+)\)", "gm");
var matches = str.match(regex);

但匹配项总是显示为空。我做错了什么?

我在regex101 尝试过这个正则表达式,它似乎可以工作,所以我不知道为什么代码不起作用。

【问题讨论】:

  • 使用RegExp 构造函数时,您需要为模式和字符串文字提供转义序列 -- new RegExp("^\\((\\d+)\\)", "gm")

标签: javascript regex string


【解决方案1】:

您需要将捕获组的结果推送到数组中,为此使用exec() 方法。

var str = '(123)abc\ndefg(456)\nhijkl\n(999)\n7'
var re  = /^\((\d+)\)/gm, 
matches = [];

while (m = re.exec(str)) {
  matches.push(m[1]);
}

console.log(matches) //=> [ '123', '999' ]

【讨论】:

    【解决方案2】:

    我看不出你的正则表达式有什么问题,试试这个从 regex101 生成的代码:

    var re = /^\((\d+)\)/gm; 
    var str = '(123)abc\ndefg(456)\nhijkl\n(999)\n7';
    var m;
    
    while ((m = re.exec(str)) !== null) {
        if (m.index === re.lastIndex) {
            re.lastIndex++;
        }
        // View your result using the m-variable.
        // eg m[0] etc.
    }
    

    Working demo

    顺便说一句,正如 jonathan lonowski 在他的评论中指出的那样,您在使用 RegExp 时必须转义反斜杠:

    new RegExp("^\\((\\d+)\\)", "gm")
    

    【讨论】:

      【解决方案3】:

      你可以使用这个正则表达式:

      var regex = /^\((\d+)(?=\))/gm;
      

      并使用捕获的组 #1

      RegEx Demo

      使用正则表达式构造函数(注意双重转义):

      var regex = new RegExp("^\\((\\d+)(?=\\))", "gm");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-30
        • 1970-01-01
        • 1970-01-01
        • 2011-12-05
        • 2017-11-17
        • 1970-01-01
        相关资源
        最近更新 更多