.NET Regex negative lookbehind not working

I am trying to match the following text (anywhere on a line) where the line may be something between A and;

Astring; 

However, I do not want to match the following

 aAstring; AAstring; 

Expression (?<![A|a])A.*?; works fine for aAstring; but not for AAstring;

Doesn't the search seem to work for the same character? I must be missing something here.

+4
source share
3 answers

The first is lookbehind, not look. To understand what is going on here, add up what the regular expression says:

 (?<![A|a])A #An A that is not preceded by A, a, or a literal | .?; #Any number of characters followed by ; 

Now consider your input, AAstring :

 A #An A that is not preceded by A (because it at the beginning of the string) Astring #Some characters followed by ; 

So lookbehind works, it just doesn't do what you think it does. I think you want something like this:

 ^(?![Aa]{2})A.*?; 

This binds itself to the beginning of the line, so you know where the lookahead will look. Here is what it means:

 ^ #Beginning of the line (?![Aa]{2}) #"The following string must not start with two As in a row, regardless of case" A.*?; #Capital A followed by anything followed by ; 

You can also try

 \b(?![Aa]{2})A.*?; 

if your target is not at the very beginning of the line.

Please note that this is actually the same as ^A(?![Aa]).*?; or \bA(?![Aa]).*?; but it may be easier to understand.

+2
source

If any string can be part of string , then it matches correctly. A in the regular expression matches the first A in the text, a .*? Astring . And before the first A there is no A or A

If you have some rules for the string part, you should add them and this should fix your problem.

+2
source

Negative appearance works correctly. To get what you're trying, I suggest using a negative forecast ahead, as shown in this template: "A(?![Aa]).*?;"

It will match A , and then won't match if the next character is either A or A If you want the line to start with A , and not as a partial match in a larger line, add the \b metacharacter at the beginning of the pattern: @"\bA(?![Aa]).*?;"

+1
source

All Articles