【问题标题】:Find all matches in string查找字符串中的所有匹配项
【发布时间】:2023-01-06 23:15:52
【问题描述】:

我正在使用正则表达式搜索匹配的字符串的所有实例你好[n]图案。

var str = 'Hello[0] hello[2] hell Welcome to JavaScript.';
var regex = /hello+/gi;
var result = str.match(regex);

上面的代码产生以下结果。

[ 'Hello', 'hello' ]

我想知道如何修改我的正则表达式以产生以下结果。

[ 'Hello[0]', 'hello[1]',..... ]

【问题讨论】:

  • /hello\[\d+\]/gi

标签: javascript regex


【解决方案1】:

如果您想要包含号码,您必须将正则表达式更改为 hello[d+]+。 工作示例:https://regex101.com/r/Xtt6ds/1

所以你得到:

var str = 'Hello[0] hello[2] hell Welcome to JavaScript.';
var regex = /hello[d+]+/gi;
var result = str.match(regex);

【讨论】:

    【解决方案2】:

    扩展您当前的正则表达式模式以包括方括号:

    var str = 'Hello[0] hello[2] hell Welcome to JavaScript.';
    var matches = str.match(/hello[.*?]/gi);
    console.log(matches);

    【讨论】:

      【解决方案3】:

      你可以这样做:

      var str = 'Hello[0] hello[2] hell Welcome to JavaScript.';
      var regex = /Hello[[0-9]+]|hello[[0-9]+]/gi;
      var result = str.match(regex);
      console.log(result);

      【讨论】:

        猜你喜欢
        • 2017-11-14
        • 1970-01-01
        • 2020-08-07
        • 1970-01-01
        • 2017-04-15
        • 2013-03-19
        • 2021-11-29
        • 2015-01-11
        • 1970-01-01
        相关资源
        最近更新 更多