gpt4 book ai didi

javascript - 如何使用正则表达式 javascript 匹配一串单词

转载 作者:行者123 更新时间:2023-11-28 17:28:03 25 4
gpt4 key购买 nike

我正在尝试找到此结果的正则表达式:

string => should be matched (a single word or set of words at the beginning or the ending)
string => should be matched (a single word or set of words in the middle)
{{string}} -- should not be matched (a single word or set of words surrounded by two "{}" should not be matched)

我在此函数中使用此正则表达式:

text = text.replace(RegExp("([^{]{2})[^(\d:)]" + aTags[index].textContent + "\w* 
([^}]{2})", 'i'), "{{" + index + ":" + aTags[index].textContent + "}}");

该函数应在“text”字符串中查找“a”标记的文本内容,并通过在文本内容的开头添加数字和“:”来替换它,以便结果应如下所示:

some text => will became => {{1:some text}}

regex on regex101

最佳答案

我们可以应用旧的 *SKIP what's to avoid approach并抛出完整匹配中不需要替换的所有内容并捕获第 1 组中所需的输出:

{{[^}]+}}|(string)

为了在 JavaScript 中有效地工作,我们必须使用 .replace 回调函数:

const regex = /{{[^}]+}}|(string)/gm;
const str = `string
string
{{string}}`;

var index = 1; //this is your index var and is somehow set from outside
const result = str.replace(regex, function(m, group1) {
if (group1) return `{{${index}:${group1}}}`;
else return m;
});
console.log('Substitution result: ', result);

我对此进行了伪编码,因为我不知道 indexaTags[index].textContent 来自哪里。根据需要进行调整。

关于javascript - 如何使用正则表达式 javascript 匹配一串单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51126550/

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