How to Fake a Negative Lookbehind in an XY Regular Expression

Please check the FAQ (https://www.xyplorer.com/faq.php) before posting a question...
Post Reply
Dustydog
Posts: 321
Joined: 13 Jun 2016 04:19

How to Fake a Negative Lookbehind in an XY Regular Expression

Post by Dustydog »

I wanted to figure out how to do the equivalent of a negative lookbehind in a regular expression even though XY's flavor doesn't support them.

What we're trying to do is capture "OK" as long as it isn't preceded by "not". If we could use negative lookbehind syntax, it would look like this:

Code: Select all

(?<!not\s)(OK)
But, we can't.

So instead:

Code: Select all

(?:(?!not\s).{4}|^.{0,3})(OK)
Sample Data:

Code: Select all

This is not OK.
This is OK.
This is OK too.
1234 OK here.
234 OK here.
34 OK here.
4 OK here.
 OK here.
OK here.
What we're essentially saying is: "Is the next thing we're trying to match a 'not'? Yes? Move on until it isn't, then try to capture what we want."

This is kind of the inverse of thinking: "'OK' is here. Is 'not' behind it? Yes? Move on until 'OK' is clear."

The {0,3} in the second half of the alternation are required for matches where 'OK' is near the beginning of the string.

This took me awhile to figure out, and I don't know if I explained it well enough. But it works, and it's easy to fill in the blanks. Just use the number of characters in what you don't want to match (plus the space) in the first half, then n-1 in the second half of the alternation.

An example of filling in the blanks is showing that it works if you want to capture "OK" as long as there's not a space before it. This can have extra code removed, but it's in there for clarity. To test it, remove a few spaces before "OK" in the sample data.

Code: Select all

(?:(?!\s).{1}|^.{0})(OK)
If someone feels like saying this more clearly, or showing an alternative, I'd certainly be happy to see it. One could, of course, not use a regular expression and use string functions - but this isn't bad.

***

And remember, if you want to add a comment in the form "(?#Anything you want to say)", Don was kind enough to allow this by stripping them out before they're evaluated even though VB doesn't support comments. This can be particularly handy if you want to add some always-there regular expressions in the rename dialogue.

Post Reply