Using negative look behind while still returning the matching subexpression

55 views Asked by At

So I can use negative look-behind to search for all occurrances of the string <ANYTHING>.dbo.TableName where <ANYTHING> is not some particular string. The problem is that the returned matches do not catch the value of <ANYTHING> subexpression. For exmaple, if I have the following text:

Test1.dbo.MyTable
Test2.dbo.MyTable
Test123.dbo.MyTable
Test223.dbo.MyTable

and I use the following regex:

(?<!Test1)\.dbo\.MyTable

It does catch all the occurrences except the first one, but the matches only contain .dbo.MyTable and not the preceding value that has been ignored by the negative look-behind. How can I catch the missing part?

2

There are 2 answers

1
hwnd On BEST ANSWER

You could precede your lookbehind with \w to match word characters in order to match the entire substring.

\w+(?<!Test1)\.dbo\.MyTable

Explanation | Live Demo

0
Lucas Trzesniewski On

Either change your regex to use a negative lookahead:

^(?!Test1)\w+\.dbo\.

Or use a positive lookbehind with a capture (this will be a variable-length lookbehind, which .NET supports):

(?<!Test1)(?<=(\w+))\.dbo\.

The first way is cleaner IMO.