Question

I need a regex to match strings that do not end in certain terms.

Input is a bunch of Class names, like Foo, FooImpl, FooTest, FooTestSuite, etc.

I want to match anything that does not end in Test, Tests, or TestSuite.

Should Match:

  • FooImpl
  • FooTestImpl
  • Foo

Should not match:

  • FooTest
  • FooTestSuite
  • FooTests

I just can't get this right. What I have now is wrong so I won't even bother posting it.

Was it helpful?

Solution

Try a negative lookbehind if your language supports it:

/(?<!Test)(<?!Tests)(<?!TestSuite)$/

Otherwise you can simulate a negative lookbehind using a negative lookahead:

/^(?!.*(?:Test|Tests|TestSuite)$).*$/

Rubular

OTHER TIPS

Negative matching is something regex can't actually do for the most part. Is there some reason you can just do !(string =~ regex)?

That's why grep has a -v (invert match) flag.

I propose an alternative solution using grep:

grep -vE ".+(Test|Tests|TestSuite)$" *

-v is negation, -E is for regex matching. Since not all languages support lookaheads and lookbehinds and grep is mostly platform independent, it could be your best bet.

You might try using a word boundary operator:

test\b|tests\b|testSuite\b

That will target words that end with those characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top