正则表达式:匹配除特定短语之外的文本段落中的所有内容

时间:2018-01-26 06:25:28

标签: javascript regex regex-negation

我正在为Google文档编写免费插件并处理文本段落。

我需要一个正则表达式来匹配除短语之外的所有内容(即用空格分隔的多个单词)。

例如,在搜索文字The quick brown fox jumped over the lazy dog时,我想匹配除quick brownlazy之外的所有内容,预期结果为The fox jumped over the dog

\b((?!(lazy)\b).)+
这有效;它匹配除lazy之外的所有文字,我得到The quick brown fox jumped over the dog

\b((?!(quick brown|lazy)\b).)+
这不起作用;它留在brown,当我得到The brown fox jumped over the dog

时,我得到The fox jumped over the dog

我在网上搜了好几个小时,没有运气。正则表达式遗漏了一些东西,我不知道它是什么。

感谢阅读!

RegEx示例: https://regex101.com/r/3HGiff/1
Javascript示例: https://jsfiddle.net/g85je2aj/16/

编辑/更新:我开发了另一种解决方案,但它依赖于积极的外观,只有Chrome支持。

((?<=(quick brown|lazy)+(?=[\s]))|^(?!(quick brown|lazy))).+?((?=(quick brown|lazy))|$)

RegEx示例: https://regex101.com/r/3HGiff/3
Javascript示例: https://jsfiddle.net/g85je2aj/19/

由于这仅适用于Chrome,我认为这不是一个真正的解决方案。关于如何修改该正则表达式而不使用lookbehind的任何想法,或者这是不可能的?

2 个答案:

答案 0 :(得分:1)

您可以使用拆分方法,而不是匹配与某些字符串不匹配的所有文本。您可以使用所需的短语列表,以避免构建基于交替的正则表达式,并将其与String#split()一起使用:

var regExp = new RegExp("\\b(?:" + phrasesToSearchFor + ")\\b","i");
var results =  textToSearchIn.split(regExp);

您稍后需要做的就是访问results数组中的所有项目。

这是JS演示:

&#13;
&#13;
$(document).ready(function() {
  $("#button").click(function () {
  //the text to search for words in, then inverse highlight
  var textToSearchIn = "The quick brown fox jumped over the lazy dog.";
  //phrases to search for in a regex-friendly format
  //please note: this string vary in length and number of phrases 
  //  as it is parsed from an array of phrases using array.join('|');  
  var phrasesToSearchFor = "quick brown|lazy";
  //build a new regular expression to match everything but the phrasesToSearchFor
  //the best regex I have figured out is:  \b((?!(quick brown|lazy)\b).)+
  //but it only works for single-word phrases
  var regExp = new RegExp("\\b(?:" + phrasesToSearchFor + ")\\b","i");
  //do a while loop to collect all the matches
  var results =  textToSearchIn.split(regExp);
  for (var result of results) {
    //format the matche as a list item.  we only need the first group [0]
    var result = $('<li>' + result + '</li>');
    //send the match to the html list
    $('#output').before(result);
  }
  /* expected output:  
     * The 
     * fox jumped over the 
     * dog.
    actual output:    
     * The 
     * brown fox jumped over the 
     * dog.
  */
  });
 });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click to test</button>
<ul id="output"></ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

或者您可以改为使用捕获组:

(.*)(one|two words)\s(.*)

然后,您可以使用以下内容获取没有指定字词的文字:$1$3

示例: regex101.com