Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: match pattern but not certain word

Tags:

regex

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?

like image 518
reox Avatar asked Sep 13 '12 12:09

reox


People also ask

How do you exclude words in regex?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

What does \b mean in regex?

The \b metacharacter matches at the beginning or end of a word.

What does \+ mean in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .

What is the difference between \b and \b in regular expression?

\B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.


1 Answers

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

like image 144
Wiseguy Avatar answered Sep 19 '22 23:09

Wiseguy