简体   繁体   English

正则表达式RE:全部但不是这种模式

[英]Regex RE: All but not this pattern

quick question... I need a regex that matches a particular letter in a code unless it is contained in a certain pattern. 快速问题...我需要一个与代码中的特定字母匹配的正则表达式,除非它包含在特定模式中。

I want something that matches N followed or preceded by anything aslong as it isn't preceded IMMEDIATELY by C(=O). 我想要一个与N匹配的东西,只要它不以C(= O)立即开头即可。

Example: 例:

C(=O)N

Should not match 不匹配

C(=O)CN

Should match 应该匹配

But it doesn't need an anchor because: 但这不需要锚点,因为:

C(=O)NCCCN

Should match because of the N at the end 应该匹配,因为最后是N

So far i have this: 到目前为止,我有这个:

(?!C\(=O\)N$)[N]

Any help would be appreciated. 任何帮助,将不胜感激。

You can use a negative lookbehind: 您可以在后面使用否定式:

(?<!C\(=O\))N

See the regex demo 正则表达式演示

The N will get matched only when not preceded immediately with a literal C(=O) sequence. 仅当不立即在字面C(=O)序列之后才可以匹配N

The (?<!...) is called a negative lookahead . (?<!...)被称为否定超前 It does not consume characters (does not move the regex index), but just checks if something is absent from the string before the current position. 它不消耗字符(不移动正则表达式索引),而只是检查当前位置之前的字符串中是否缺少某些内容。 If the text is matched, the match is failed (there is no match). 如果文本匹配,则匹配失败(不匹配)。 See Lookarounds for more details. 有关更多详细信息,请参见环顾四周

In Python : r'(?<!C\\(=O\\))N' : 在Python中r'(?<!C\\(=O\\))N'

import re
p = re.compile(r'(?<!C\(=O\))N')
strs = ["C(=O)N", "C(=O)CN", "C(=O)NCCCN"]
print([x for x in strs if p.search(x)])

Use a negative look-behind instead: 改用负向后看:

(?<!C\(=O\))N

See this regex101 example . 请参见此regex101示例

Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM