正则表达式:从匹配中排除模式

RegEx: Excluding a pattern from the match

我了解 RegEx 的一些基础知识,但不是专家。我正在学习它。目前,我正在使用以下非常非常简单的正则表达式来匹配给定句子中的任何数字。

/d

现在,我希望除了一些模式(如 e074663 OR e123444 OR e7736)之外的所有数字都应该从匹配中排除。所以对于以下输入,

Edit 398e997979 the Expression 9798729889 & T900980980098ext to see e081815 matches. Roll over matches or e081815 the expression e081815 for details.e081815 PCRE & JavaScript flavors of RegEx are e081815 supported. Validate your expression with Tests mode e081815.

只能匹配粗体数字,不能匹配任何 e081815。我尝试了以下但没有成功。

(^[e\d])(\d)

此外,今后还需要添加更多模式以进行排除。例如cg636553 或 cg(任何数字)。在这方面的任何帮助将不胜感激。谢谢!

试试这个:

(?<!\be)(?<!\d)\d+

测试一下live on regex101.com

解释:

(?<!\be) # make sure we're not right after a word boundary and "e"
(?<!\d)  # make sure we're not right after a digit
\d+      # match one or more digits

如果你想匹配单个数字,你可以使用\G匹配成功后匹配位置的锚点来实现:

(?:(?<!\be)(?<=\D)|\G)\d

Test it here

另一种选择是使用带环视的捕获组

(?:\b(?!e|cg)|(?<=\d)\D)[A-Za-z]?(\d+)
  • (?:非捕获组
    • \b(?!e|cg)字界,断言直接右边的不是ecg
    • |
    • (?<=\d)\D 匹配除数字以外的任何字符,断言直接在左边的是数字
  • ) 关闭群组
  • [A-Za-z]? 匹配可选字符 a-zA-Z
  • (\d+)组 1
  • 中捕获 1 个或多个数字

Regex demo