是否有一个 Regex 表达式来匹配除特定字符串中出现的所有字母?

Is there a Regex expression to match all occurrences of a letter except in a certain string?

我试图找到一个 Regex 表达式来匹配小写 [a-z] 单词字符串中出现的任何字母,除非在特定单词中找到该字母。单词被空格包围,除了第一个和最后一个单词,因为它们位于字符串的开头和结尾。

具体来说,我想匹配字符串中的任何 'f',但在单词 'def' 中除外。我过去对正则表达式的经验很少。

例如,给定这个字符串:

'def half def forbidden fluff def def tough off definite def'

表达式应该 select 只有 'f' 加粗:

'def half def forbidden fluff def def tough off definite def'

你可以试试:

f(?<!\bdef\b)

上面正则表达式的解释:

f - Matching f literally.

(?<!\bdef\b) - Represents a negative look-behind not matching any occurrence of the word def. If you want def to be case-insensitive then please use the flag \i.

\b - Represents a word boundary for matching the exact word (in this case def) or characters inside.

你可以在here.

中找到上述正则表达式的演示

使用像

这样的 PCRE 模式
(?<!\S)def(?!\S)(*SKIP)(*FAIL)|f

参见 proof。它在空白边界内匹配 def,并跳过匹配,并在所有其他地方匹配 f

如果您想使其不区分大小写,请添加 (?i):

(?i)(?<!\S)def(?!\S)(*SKIP)(*FAIL)|f