在前面的文章中没有提到的情况下,在Javascript中对正则表达式求反

Negating a regular expression in Javascript in situations not covered in earlier posts

本文关键字:Javascript 正则表达式 文章 在前面 情况下      更新时间:2023-09-26

在您将此标记为重复之前,请允许我向您保证,我已经完成了关于stackoverflow主题的所有问题,包括以下问题:

如何在JavaScript中反转正则表达式?

正则表达式 中的

反式

我正在尝试用语法解析字符串,如下所示:

 contents = "Some Random Text1 <@@Matched text 1@@> Some Random Text2 <@@Matched text 2@@> Some Random Text3";

我使用正则表达式:

 reg_exp = /'<'!'!.*?'!'!'>/g   

,然后使用以下代码提取匹配的文本,并从中生成一个长字符串,每个匹配之间使用空白分隔符。

 while ((matched_array = reg_exp.exec(contents)) != null) {
     matched_text +=  (matched_array[0] + "");
 };

返回matched_text为:

  <@@Matched text 1@@> <@@Matched text 2@@> 

所有这些都可以正常工作。现在我想获得匹配文本之外的所有文本的子字符串。

我不能设置一个正则表达式对匹配文本之外的文本做同样的事情,为上面的例子生成以下结果字符串:

  Some Random Text1 Some Random Text2 Some Random Text3

我尝试了上面提到的所有可能的解决方案,包括(?!或^ after grouping()等

使用string.replace函数将匹配的字符替换为空字符串

var string =  "Some Random Text1 <@@Matched text 1@@> Some Random Text2 <@@Matched text 2@@> Some Random Text3";
alert(string.replace(/'s*<@@.*?@@>/g, ''))