Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A regular expression to exclude a word/string

Tags:

regex

I have a regular expression as follows:

^/[a-z0-9]+$ 

This matches strings such as /hello or /hello123.

However, I would like it to exclude a couple of string values such as /ignoreme and /ignoreme2.

I've tried a few variants but can't seem to get any to work!

My latest feeble attempt was

^/(((?!ignoreme)|(?!ignoreme2))[a-z0-9])+$ 

Any help would be gratefully appreciated :-)

like image 343
romiem Avatar asked Jan 16 '10 21:01

romiem


People also ask

How do you skip a word in regular expressions?

contain the word FOO followed by a non-word (whitespace, etc) character (\W), then the matching will be made against \S+ (one or more non whitespace characters). So you'll get the second part of the word in your \1, $1, etc. If you want to ignore all sub-strings starting with FOO, you can get rid of that \W.

What does \b mean in regular expressions?

Simply put: \b allows you to perform a “whole words only” search using a regular expression in the form of \bword\b. A “word character” is a character that can be used to form words. All characters that are not “word characters” are “non-word characters”.


2 Answers

Here's yet another way (using a negative look-ahead):

^/(?!ignoreme|ignoreme2|ignoremeN)([a-z0-9]+)$  

Note: There's only one capturing expression: ([a-z0-9]+).

like image 126
Seth Avatar answered Oct 09 '22 13:10

Seth


This should do it:

^/\b([a-z0-9]+)\b(?<!ignoreme|ignoreme2|ignoreme3) 

You can add as much ignored words as you like, here is a simple PHP implementation:

$ignoredWords = array('ignoreme', 'ignoreme2', 'ignoreme...');  preg_match('~^/\b([a-z0-9]+)\b(?<!' . implode('|', array_map('preg_quote', $ignoredWords)) . ')~i', $string); 
like image 29
Alix Axel Avatar answered Oct 09 '22 13:10

Alix Axel