正则表达式 - 将单词与共享空间匹配

Regex - Match words with shared spaces

如何匹配句子中的指定单词? 如果我有句子 "lord of the rings" 并想删除 "of" 和 "the" 我该如何编写正则表达式?

我不希望它匹配 "don't match them" 或 "don't match often" 中的任何内容。当 "the" 或 "of" 也在行的开头或结尾时,它应该匹配。

我遇到的问题是当单词像 "lord of the rings" 的示例中那样彼此跟随时。当他们分享 space 可以这么说。

我能做到的最好的事情是这样的:

/^(the|of) | (the|of)$| (of|the) /gmi

但这并不能解决我所有的问题。

/(of\s.*the\s)/gmi行吗?还是我误解了你想做什么? 这将找到句子中第一个 'of ' 到最后一个 'the ' 之间的所有内容。

您可以使用前瞻组 (?= ) [doc]:

/^(the|of) | (the|of)$| (of|the)(?= )/gmi

演示:https://regex101.com/r/Bo4Ur1/1

这是一个完美的单词边界任务

\b(of|the)\b