2

I have 15 titles as follows:

fruits-and-flowers-themeA
fruits-and-flowers-themeB
fruits-and-flowers-just-test-themeA
themeAfruitsandflowers
nice-fruits-and-flowers-themeA
botanical-names-themeA

I want a regex to help me get only those titles with "themeA" in them, but it should not include "nice" and not include "just-test" or "just-tests".

I tried

^(?!.*just-test|*just-tests|nice).*?(?:themeA).*,

but I still get fruits-and-flowers-just-test-themeA in the output.

How to fix this?

Thanks

1
  • What language are you using? There are more options depending on language.
    – zx81
    Jun 10, 2014 at 22:10

3 Answers 3

4

You can use this regex with negative lookahead:

^(?!.*?(?:just-tests?|nice)).*?themeA.*$

Working Demo

1
  • 1
    Thanks for the edit and the answer. Both your answer and Zx81's answer works. I had to chose one! Jun 11, 2014 at 23:45
2

Option 1

You can use a single regex with lookaheads (see online demo):

^(?!.*nice?)(?!.*just-tests?).*themeA.*
  1. The ^ asserts that the match starts at the beginning of the string (so we don't match a subset of the string
  2. The (?!.*nice?) is a negative lookahead that asserts that at this position in the string, we cannot find any characters followed by nice
  3. The (?!.*just-tests?) is a negative lookahead that asserts that at this position in the string, we cannot find any characters followed by just-test and an optional s

As a further tweak, you can compress the lookaheads into one using an | alternation as in anubhava's answer.

Option 2 without lookaheads (Perl, PHP/PCRE)

^(?:.*(?:nice|just-tests?).*)(*SKIP)(?!)|.*themeA.*

This one doesn't use lookaheads but just skips the unwanted titles. See demo.

0

Use two different regular expressions for clarity and simplicity.

Match your string against one regex that matches themeA:

/themeA/

and then check that the string does NOT match the one you don't want:

/nice|just-tests?/

Doing it in two different regexes makes it far easier to understand and maintain.

Your Answer

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

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