正则表达式 - 匹配除特定字符串以外的任何内容 [英] Regex - match anything except specific string

查看:49
本文介绍了正则表达式 - 匹配除特定字符串以外的任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个正则表达式(将用于 ZF2 路由,我相信它使用了 php 的 preg_match)来匹配除特定字符串之外的任何内容.

I need a regex (will be used in ZF2 routing, I believe it uses the preg_match of php) that matches anything except a specific string.

例如:我需要匹配除red"、green"或blue"之外的任何内容.

For example: I need to match anything except "red", "green" or "blue".

我目前有正则表达式:

^(?!red|green|blue).*$

test -> match (correct)
testred -> match (correct)
red -> doesn't match (correct)
redtest -> doesn't match (incorrect)

在最后一种情况下,正则表达式的行为不像我想要的.它应该匹配redtest",因为redtest"不是(red"、green"或blue").

In the last case, the regex is not behaving like I want. It should match "redtest" because "redtest" is not ("red", "green" or "blue").

关于如何修复正则表达式的任何想法?

Any ideas of how to fix the regex?

推荐答案

你可以在前瞻中包含字符串锚点的结尾

You can include the end of string anchor in the lookahead

 ^(?!(red|blue|green)$)

这篇关于正则表达式 - 匹配除特定字符串以外的任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆