Powerful searches in DDE: Regex for ‘all bar that don’t start with foo’

Regexes are wonderful. There’s a learning curve, and they are very cryptical to be able to read, let alone write, but once you get the hang of it they are wonderful.

I was doing some refactoring and I wanted to see all instances of a function called ‘AddButton’ – and my results got saturated with another function ClickAddbutton.

Which Regex to use to ask for ‘Show me all AddButtons but ignore ClickAddButton’?

The trick here is to use negative lookbehind:

(?<!textIDontWantPrefixed)TextIAmLookingFor

so in my example this was what to input in the search box in DDE:

(?<!Click)AddButton

This is the way it works:

1. Search for ‘AddButton’

2.When you’ve found ‘AddButton’, look if there is a naughty prefix (‘Click’) which invalidates the search.

This is the lookbehind part. It’s slightly confusing because a lookbehind is going to look at the bits to the left of the word, which one would typically call ‘before’. The regex convention is that forwards is the direction of parsing and behind is the other direction.

3. if the naughty prefix isn’t there, return a match.

That’s the negative part.

VoilĂ !

P.S. an excellent tool for Regexes is RegExBuddy (Windows only though). Really recommended, saved me loads and loads of time. I wouldn’t do regexes without it.

Leave a Comment