正则表达式 - 匹配除特定字符串以外的任何内容

标签 regex preg-match regex-negation

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

例如:我需要匹配除“red”、“green”或“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”)。

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

最佳答案

您可以在前瞻中包含字符串 anchor 的结尾

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

关于正则表达式 - 匹配除特定字符串以外的任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16930563/

相关文章:

c# - 包含 "|"的正则表达式

python - 正则表达式组 : How to get the desired output with a more specific match pattern?

php - 在 PHP 正则表达式中使用 ^ 和 $ 出现意外结果?

php - 正则表达式只验证自然数?

php - 如何从 php 中的用户输入中删除 http、https、slash、www

regex - 成对括号的正则表达式

用于捕获两个字符分隔符的正则表达式模式

php - 如果不包含 "{"和 "}",则抓取 {...} 内的所有字符

c# - Regex.Split 特定字符

php - 如何在 Laravel 5.4 中验证文件名