Iceman
Iceman

Reputation: 80

Positive lookbehind not working as expected

I have a little problem matching strings using .net regular expressions. For example I have the following string:

II Kop 15 / 1544

And I want to match the second number following the / character. Additionally I only want to match that number when there is a preceding number followed by a slash. Also this number must only be 2 or 4 digits.

I came up with something like this:

(\b[0-9]{2}\b|\b[0-9]{4}\b)

It matches 2 or 4 digit numbers , as it matched here 15 and 1544. Now I'm trying positive lookbehind:

(\b[0-9]{2}\b|\b[0-9]{4}\b)(?<=(\b[0-9]{0,10}\b)\s*(/)\s*)

Not match. What am I doing wrong? Please help.

Upvotes: 1

Views: 812

Answers (1)

zolo
zolo

Reputation: 469

It's simpler to place the look behind before your capturing group.

(?<=[0-9] / )([0-9]{4}|[0-9]{2})

Variable length look-behind is allowed in .NET, so you can also write the regex as:

(?<=[0-9]\s*/\s*)([0-9]{4}|[0-9]{2})

Upvotes: 2

Related Questions