18

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"?

3
  • Should getDetailsAndBars match or not?
    – Qtax
    Feb 17, 2012 at 17:57
  • should getInfo match? your original regex appears to exclude that case.
    – Gus
    Feb 17, 2012 at 18:15
  • 4
    Why do you have the question mark in [Gg]et?? The ? just makes the t optional. Was that your intention? Feb 17, 2012 at 18:51

2 Answers 2

17

Something like this could work for you:

\b[Gg]et(?!\w*[Dd]etails)\w+s\b
1
  • 4
    The negative lookahead (?!...) makes sure that Details is not part of that match, \bs are used to anchor the match at the beginning/end of words, otherwise GetBars would match in this sting setGetBarsX.
    – Qtax
    Feb 17, 2012 at 18:08
10

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)

5
  • You may want a trailing \b or $ on there, so that you don't match getSass in getSassDetails.
    – Phrogz
    Feb 17, 2012 at 17:52
  • Awesome! Thats closer. But it looks like its still matching strings with details: regexr.com?301ut can you tell me how to exclude those strings? Feb 17, 2012 at 17:54
  • -1, ? after the t is wrong, and op seems to indicate that Details doesn't have to be adjacent to get.
    – Qtax
    Feb 17, 2012 at 17:55
  • @Qtax oops, yes copied that from his original, was thinking about the negative match aspect and didn't notice that.
    – Gus
    Feb 17, 2012 at 18:07
  • actually the negative look behind covers the cases you put in regexr, but not getSomeDetailsAndNotOthers... so if you need to exclude that too then use Qtax's solution. I was only trying to exclude things ending in "details"...
    – Gus
    Feb 17, 2012 at 18:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.