匹配除特定短语外的所有内容

Match all except certain phrase

我发现了很多关于“匹配字符串中除单个单词之外的所有内容”的问题。但是,其中 none 不适用于短语(两个或多个单词组合)的情况。假设我有一个字符串,如示例 (RegEx)。我想匹配单个单词 + 10 位数字的所有可能组合,某些 combination/phrase“nip + 10 位数字”除外(+ 表示简单的 space)。在我的示例中,我使用 \bnip\s*\d{10}\b 来匹配“nip + 10 位数字”,但我想匹配所有 extept“nip + 10 位数字”。 hello 也不应匹配,因为右侧缺少 10 位数字。如有任何帮助,我们将不胜感激。
示例:

   hello 
   alpha 1111111111 # should be matched
   allla 2322322321 # should be matched
   nip 5260305006 
   pin 5260305006 # should be matched
   nipp 5260305006 # should be matched

您可能会使用

 \b(?!nip\b)\S+\s*\d{10}\b

说明

  • \b(?!nip\b)一个字界,断言直接右边的不是nip和一个字界
  • \S+\s* 匹配 1+ 个非白色 space 字符后跟可选的白色 space 字符 (或者使用 \w+ 而不是 \S+ 只匹配单词字符)
  • \d{10}\b 匹配 10 个数字后跟一个单词边界

Regex demo

如果您想要 want to match all possible combination of a single word + 10-digits 并且不想匹配 nip + 10-digits number" (+ means a simple space),您可以将其从匹配中排除,包括 space 和 10 位数字。

注意 这确实匹配 nip5260305006 因为中间没有 space。

\b(?!nip \d{10}\b)\S+\s*\d{10}\b

Regex demo