匹配模式前面或后面都没有字符串 [英] Match pattern not preceded or followed by string
问题描述
我需要匹配任何 9 个或更多数字的序列,该序列前面没有 OR 后跟 2 个大写字母,文本中的任何位置:
I need to match any sequence of 9 digits or more, that is not preceded OR followed by 2 uppercase letters, anywhere in a text:
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
我尝试了以下失败:
I've tried unsuccessfully the following:
(?![A-Z]{2}(\d{9,})[A-Z]{2})(\d{9,})
这个忽略了负面的前瞻,仅仅因为它可以从任何地方开始
结合 Negative Lookahead 和 Negative Lookbehind,我可以进行 AND 运算,但不能进行 OR 运算:
With a combination of Negative Lookahead and Negative Lookbehind, I was able to have a AND operation working on, but not a OR operation:
(?<![A-Z]{2})(\d{9,})(?![A-Z]{2})
如果前面没有2个大写字母AND后面没有2个大写字母
This one only matches if not preceded by 2 uppercase letters AND not followed by 2 uppercase letters
所以,问题是:是否可以仅使用正则表达式?
So, the question is: is it possible with just Regex?
信息:
1 - 目标引擎是 .Net,所以我可以使用可变长度负向后视.
1 - The target engine is .Net, so I'm able to use variable length negative lookbehind.
2 - 我不能使用 start string
和 end string
锚点(至少,我认为我不能),因为我的匹配可能在字符串,甚至可能在同一个字符串(文本)上多次出现.
2 - I can't use start string
and end string
anchors (at least, I think that I can't), because my match could be anywhere in the string, and could even happen multiple occurrences on a same string(text).
3 - 这不是重复的.我在任何地方都找不到带有前后序列/字符串的 OR 条件.我发现最接近的是试图匹配后面没有字符的模式的人,他/她可以使用开始字符串和结束字符串锚点.
3 - This is not a duplicate. I could not found anywhere the OR condition with preceded and followed sequences/strings. The closest that I found was someone that was trying to match a pattern not followed by a character, and He/She could make use of start string and end string anchors.
4 - 我已经找到并尝试过的:
4 - What I already found and tried:
javascript正则表达式,word not后跟而不是特定字符
正则表达式 - 匹配字符串前面没有另一个字符串 (JavaScript)
https://superuser.com/questions/477463/is-it-possible-to-use-not-in-a-regular-expression-in-textmate
推荐答案
第二次尝试执行逻辑 AND 后,您就快完成了.只需使用 |
将两种可能的情况分开:
With your second attempt, that performs a logical AND, you are almost there. Just use |
to separate the two possible scenarios:
(?
这篇关于匹配模式前面或后面都没有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!