Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Pattern \K Alternatives in C#

Tags:

c#

regex

I have a regex expression that I tested on http://gskinner.com/RegExr/ and it worked, but when I used it in my C# application it failed.

My regex expression: (?<!\d)\d{6}\K\d+(?=\d{4}(?!\d)) Text: 4000751111115425 Result: 111111

What is wrong with my regex expression?

like image 655
XandrUu Avatar asked Jan 07 '13 17:01

XandrUu


People also ask

What is ?! In regex?

It's a negative lookahead, which means that for the expression to match, the part within (?!...) must not match. In this case the regex matches http:// only when it is not followed by the current host name (roughly, see Thilo's comment).

How do I not match a character in regex?

There's two ways to say "don't match": character ranges, and zero-width negative lookahead/lookbehind. Also, a correction for you: * , ? and + do not actually match anything. They are repetition operators, and always follow a matching operator.


1 Answers

This issue you are having is that .NET regular expressions do not support \K, "discard what has been matched so far".

I believe your regex translates as "match any string of more than ten \d digits, to as many digits as possible, and discard the first 6 and the last 4".

I believe that the .NET-compliant regex

(?<=\d{6})\d+(?=\d{4})

achieves the same thing. Note that the negative lookahead/behind for no-more-\ds is not necessary as the \d+ is greedy - the engine already will try to match as many digits as possible.

like image 65
Rawling Avatar answered Sep 25 '22 12:09

Rawling