RegExp 匹配除给定单词之外的所有文本部分

RegExp Match all text parts except given words

我有一个 text,我需要用 regexp

匹配除给定单词之外的所有文本部分

例如,如果文本是 ' Something went wrong and I could not do anything ',给定的单词是 'and''not',那么结果必须是 ['Something went wrong', 'I could', 'do anything']

请不要建议我使用 string.split()string.replace() 等。我知道如何使用内置方法执行此操作的几种方法。我想知道是否有一个正则表达式可以做到这一点,当我执行 text.math(/regexp/g)

请注意,正则表达式必须至少在Chrome下有效,Firefox 和 Safari 版本不低于当前的 1 by 3!在问这个问题的时候,实际版本分别是 100.0、98.0.2 和 15.3。例如,您不能在 Safari

中使用 lookbehind 功能

请在回答我的问题之前,前往 https://regexr.com/ 检查您的答案!。您的正则表达式应突出显示句子的所有部分,包括需要部分的单词之间的空格以及需要部分周围的空格除外,除了给定的单词

在问这个问题之前,我尝试进行自己的搜索,但此链接对我没有帮助。我也试过不被接受的答案:

Match everything except for specified strings

Regex: match everything but a specific pattern

Regex to match all words except a given list

Regex to match all words except a given list (2)

Need to find a regular expression for any word except word1 or word2

Matching all words except one

Javascript match eveything except given words

进一步查看编辑

你可以使用这个正则表达式,它只使用前瞻:

/(?!and|not)\b.*?(?=and|not|$)/g

解释:

(?!and|not) - andnot

的负面展望

\b - 匹配单词边界,以防止匹配 ndot

.*? - 匹配任何字符零次或多次,尽可能少

(?=and|not|$) - 向前看 andnotend of text

如果您的文本有多行,您可以添加 m 标志(多行)。或者,您可以将点 (.) 替换为 [\s\S].

编辑:

我稍微修改了一下,所以 space 周围的禁用词被删除了:

/(?!and|not)\b\w.*?(?= and| not|$)/g

我添加了一个 \w 字符匹配以将匹配的开始推到 space 之后,并在前瞻中添加了 spaces。

Edit2:(处理单词周围的多个space):

你们非常亲密!您只需要在美元符号前加一个 \s* 并指定单词:

/(?!and|not|\s)\b.*?(?=\s*(and|not|$))/g

已更新 link:regexr.com

在 javascript 中仅使用匹配和前瞻是可能的。

/\b(?=\w)(?!(?:and|not)\b).*?(?=\s+(?:and|not)\b|\s*$)/gi

在 RegExr 上测试 here

基本匹配非受限词的开头
\b(?=\w)(?!(?:and|not)\b)
然后是惰性匹配,直到下一个空格和限制词,或者不包括最后一个空格的行尾。
.*?(?=\s+(?:and|not)\b|\s*$)

测试片段:

const re = /\b(?=\w)(?!(?:and|not)\b).*?(?=\s+(?:and|not)\b|\s*$)/gi

let str = `   Something went wrong    and    I could   not   do anything   `;
let arr = str.match(re);
console.log(arr);