bittersweetryan
bittersweetryan

Reputation: 3443

Regex that will exclude a capture group

I'm writing a regex that I need to catch strings that are plurial starting with "get". For instance getContacts and getBuildings should match the regex. However there are times where the text may equal getDetails or get**Details. I do not want the regex to include these.

I can come up with a regex that includes the matching group "Details", but I want to exclude that capture group, not include it.

[Gg]et?\w+([Dd]etail)s

I'm not very strong at regex but heres my understanding of what I wrote:

match "g" or "G" followed by "et" then optionally any word character, then the matching group, followed by "s".

How can I exclude results that have the word "details"?

Upvotes: 20

Views: 88827

Answers (2)

Gus
Gus

Reputation: 6871

I believe you are looking for zero-width negative lookahead...

http://www.regular-expressions.info/lookaround.html

[Gg]et(?![Dd]etail)\w+s

Assuming you want to exclude "Get Details", and "Get Info" but accept "Get Pages" and "Get MyDetails" (N.B. the trailing s in your original regex excludes "Get Info" already)

Upvotes: 10

Qtax
Qtax

Reputation: 33908

Something like this could work for you:

\b[Gg]et(?!\w*[Dd]etails)\w+s\b

Upvotes: 18

Related Questions