【发布时间】:2026-02-22 16:55:01
【问题描述】:
我需要匹配任何 9 位或更多位的序列,即在文本中的任何位置不以 OR 后跟 2 个大写字母:
OG237338070BR // should NOT match
og237338070br // should match
oG237338070bR // should match
G237338070BR // should match
OG237338070B // should match
G237338070B // should match
asd OG237338070BR asd // should NOT match
asd G237338070BR asd // should match
asd OG237338070B asd // should match
asd OG237338070Basd asd // should match
asd OG237338070BRasd asd // should NOT match
我尝试了以下方法失败:
(?![A-Z]{2}(\d{9,})[A-Z]{2})(\d{9,})
这个忽略了负前瞻,只是因为它可以从任何地方开始
结合 Negative Lookahead 和 Negative Lookbehind,我可以进行 AND 操作,但不能进行 OR 操作:
(?<![A-Z]{2})(\d{9,})(?![A-Z]{2})
只有在前面没有 2 个大写字母 AND 后面没有 2 个大写字母时才匹配
所以,问题是:仅使用 Regex 是否可行?
信息:
1 - 目标引擎是 .Net,所以我可以使用可变长度的负向回溯。
2 - 我不能使用 start string 和 end string 锚点(至少,我认为我不能),因为我的匹配项可能在字符串中的任何位置,甚至可能在同一个匹配项上多次出现字符串(文本)。
3 - 这不是重复的。我在任何地方都找不到带有前后序列/字符串的 OR 条件。我发现的最接近的是有人试图匹配一个不跟随字符的模式,他/她可以使用开始字符串和结束字符串锚点。
4 - 我已经找到并尝试过的:
Match only if not preceded or followed by a digit
javascript regex, word not followed and not preceded by specific char
Regular Expression - Match String Not Preceded by Another String (JavaScript)
Match pattern not preceded by character
Regex match exact word not preceded or followed by other characters
https://superuser.com/questions/477463/is-it-possible-to-use-not-in-a-regular-expression-in-textmate
【问题讨论】: