A regular expression to exclude a word/string

2019-01-01 04:57发布

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 :-)

标签: regex
3条回答
墨雨无痕
2楼-- · 2019-01-01 05:16

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);
查看更多
看风景的人
3楼-- · 2019-01-01 05:24

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

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

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

查看更多
何处买醉
4楼-- · 2019-01-01 05:36

As you want to exclude both words, you need a conjuction:

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

Now both conditions must be true (neither ignoreme nor ignoreme2 is allowed) to have a match.

查看更多
登录 后发表回答