gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:10:48 25 4
gpt4 key购买 nike

在交互式表单的构造中,我需要解析用户提交的一些正则表达式,找到每个正则表达式中捕获的每个匹配项并获取它们的索引(捕获组开始的位置)以修改原始字符串(假设添加例如捕获周围的一些 <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

关于javascript - 用正则表达式匹配每个事件并在字符串中获取它们的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18123139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com