将每个事件与正则表达式匹配,并在字符串中获取它们的索引

Match every occurences with regex and get their indexes in string

本文关键字:字符串 获取 索引 事件 正则表达式      更新时间:2023-09-26

在构建交互式表单时,我需要解析用户提交的一些正则表达式,找到每个正则表达式中的每个匹配捕获并获取它们的索引(捕获组开始的位置(以修改原始字符串(例如,假设在捕获周围添加一些<strong>标签(。
最后,我希望能够将ip:(.+);port:('d+)修改为例如ip:<strong>(.+)</strong>;port:<strong>('d+)</strong>

目前我有这一小段代码:

// Called somewhere after user entered every regex he wants
$('input.regex').each(function () {
    pattern = $(this).val(); // for non jQuery guys: just returns the content of the input
    captures = pattern.match(/('([^'(')]+'))/g);
    for(idx in captures) {
        console.log(captures[idx]);
    }
});

这会返回我找到的每个捕获组(承认用户无法键入子组...是的,正则表达式已经有点头疼了:-((当我在一些例子上运行它时,我得到了我目前想要的:

  • ip:(.+);port:('d+) 上,输出(.+)('d+)
  • ip:(?P<sourceip>['d'.]);port:('d{2,5}),输出(?P<sourceip>['d'.])('d{2,5})

现在我想要的是获取每次捕获开头的索引。我知道有 indexOf,但我可以多次进行相同的捕获。例如:

  • id1:('d+);id2:('d+) 当前输出 ('d+)('d+) 。很容易获得第一个索引,但第二个索引...

是否有可能获得类似于这样的结构:[{'match': '('d+)', 'index': 4}, {'match': '('d+)', 'index': 14}]我可以通过一些字符串操作来做到这一点,但我想知道是否有更简单(和更干净(的方法。

我会为此使用RexExp.exec((。它在 RexExp 上运行并将其与字符串匹配,但最重要的是,它返回每个匹配项的数组,可以像这样迭代。

var match; //Match object.
var matches = []; //Matches return, Array filled with match records.
var regex = "..."; //Current Regex.
var string = "..."; //Current String.
while((match = regex.exec(string)) !== null){
    var matchRecord = {};
    matchRecord.match = regex;
    matchRecord.index = match.index; //Might want to increment by 1 to make Human Readable?
    matches.push(matchRecord);
}

注意:有关 regexp.exec 的更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec