Regex for selecting words ending in 'ing' unless

Viewed 1669

I want to select words ending in with a regular expression, but I want exclude words that end in thing. For example:

everything
running 
catching 
nothing

Of these words, running and catching should be selected, everything and nothing should be excluded.

I've tried the following:

.+ing$

But that selects everything. I'm thinking look aheads/look arounds could be the solution, but I haven't been able to get one that works.

Solutions that work in Python or R would be helpful.

3 Answers

In python you can use negative lookbehind assertion as this:

^.*(?<!th)ing$

RegEx Demo

(?<!th) is negative lookbehind expression that will fail the match if th comes before ing at the end of string.

Note that if you are matching words that are not on separate lines then instead of anchors use word boundaries as:

\w+(?<!th)ing\b

Something like \b\w+(?<!th)ing\b maybe.

You might also use a negative lookahead (?! to assert that what is on the right is not 0+ times a word character followed by thing and a word boundary:

\b(?!\w*thing\b)\w*ing\b

Regex demo | Python demo

Related