繁体   English   中英

如何使用正则表达式javascript匹配字符串

[英]how to match a string of words using regex javascript

我正在尝试为此结果找到一个正则表达式:

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'标签的textContent,并在textContent的开头添加一个数字和':'来替换它,以便结果应如下所示:

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

regex101上的正则表达式

我们可以应用旧的* SKIP来避免出现问题 ,并在完全匹配中抛出不需要替换的所有内容,并在第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正则表达式中使用诸如(*SKIP)(*F)类的PCRE动词,即,您不能仅使用正则表达式来跳过文本的匹配部分。 在JavaScript中,您可以匹配并捕获要在替换回调方法中稍后分析的字符串的一部分(JS String#replace接受回调作为替换参数 )。

因此,在您的情况下,解决方案看起来像

text = text.replace(RegExp("{{.*?}}|(" + aTags[index].textContent + ")", "gi"),
    function ($0, $1) { 
        return $1 ? "{{" + index + ":" + $1 + "}}" : $0; 
    }
);

我了解aTags[index].textContent值是字母数字,否则,请考虑转义它以用于正则表达式模式

该模式将匹配内部没有}{{...}}子字符串( {{.*?}} )或( | ),它将匹配并将文本内容( (aTags[index].textContent) )捕获到组1。获得匹配项时,您需要向回调传递2个参数,整个匹配项和组1值。 如果组1不为空,则执行字符串操作,否则,只需插入匹配项即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM