10

Is there a possibility to write a regex that matches for [a-zA-Z]{2,4} but not for the word test? Or do i need to filter this in several steps?

3
  • 1
    A tip: always specify which language and regex engine you're using; they're often different. Commented Sep 13, 2012 at 12:39
  • if you plan to replace every 2-4 character word in a string, you should mention that too, because depending on the solution parts of "test" could match too. but then there are other solutions more helpful Commented Sep 13, 2012 at 12:48
  • no its just for matching a string like this: foobar.aaa.dsf but there are strings like foobar.test.dsf i dont want to match. so its not about replacing something or so. Commented Sep 14, 2012 at 8:53

2 Answers 2

17

Sure, you can use a negative lookahead.

(?!test)[a-zA-Z]{2,4}

I don't know if you'll need it for what you're doing, but note that you may need to use start and end anchors (^ and $) if you're checking that an entire input matches that pattern. Otherwise, it could match something like ouaeghAEtest because it will still find four chars somewhere that aren't "test".

Sign up to request clarification or add additional context in comments.

2 Comments

Also, for multiple word exclusions: (?![test1,test2])[a-zA-Z]{2,4}
@shrx Not quite. You've used a character class, so the lookahead will only match against the first character if it is one of those listed. (diagram) So it will reject any word that begins with a t, e, s, 1, ,, or 2. Use the pipe "or" operator instead: (?!test|foo|bar)[a-zA-Z]{2,4} (diagram)
-1
[A-Za-su-z][A-Za-df-z]{0,1}[A-Za-rt-z]{0,1}[A-Za-su-z]{0,1}

just a idea, haven't use real code to try

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.