如何使用正则表达式查找 "transparent" 以外的命名颜色
how find named colors except "transparent" by using regex
我要找
- 所有带有名称的背景颜色("red"、"blue" 等),
- 除了 "none" 和 "transparents"。
- 而且这些不应该被“//”注释掉。
不幸的是,使用这个正则表达式我仍然找到“transparent”:
(^\s*background:\s*)[a-z]{3,10};
源代码示例:
background: #fff; // should not be found
background: transparents; // should not be found, but is found
// background: blue; // should not be found
background: blue; // should be found
使用负面展望:
^\s*background:\s*(?!transparents|none)[a-z]{3,};
我将匹配更改为不限制长度,因为 transparents
无论如何都不会匹配 12 个字符长(不是您的正则表达式指定的 10) .
我还删除了不必要的括号。
在大 CSS ^
锚点内不起作用。在 PCRE 中尝试 (*SKIP)(*FAIL)
:
//\N*(*SKIP)(*F)|background:\s*(?!transparent|none)\w+
这也关心注释行。您当前的正则表达式不排除任何东西。由于 PCRE 支持这些类型的结构,它应该受益于负前瞻。
您可以使用正数 lookahead with an alternation 而不是 {3,10}
您可以使用 +
来匹配一个字符一次或多次。
(^\s*background:\s*)(?!\b(?:none|transparent)\b)[a-z]+;
如果您不再指那个组,您也可以省略 (^\s*background:\s*)
周围的括号。
我要找
- 所有带有名称的背景颜色("red"、"blue" 等),
- 除了 "none" 和 "transparents"。
- 而且这些不应该被“//”注释掉。
不幸的是,使用这个正则表达式我仍然找到“transparent”:
(^\s*background:\s*)[a-z]{3,10};
源代码示例:
background: #fff; // should not be found
background: transparents; // should not be found, but is found
// background: blue; // should not be found
background: blue; // should be found
使用负面展望:
^\s*background:\s*(?!transparents|none)[a-z]{3,};
我将匹配更改为不限制长度,因为 transparents
无论如何都不会匹配 12 个字符长(不是您的正则表达式指定的 10) .
我还删除了不必要的括号。
在大 CSS ^
锚点内不起作用。在 PCRE 中尝试 (*SKIP)(*FAIL)
:
//\N*(*SKIP)(*F)|background:\s*(?!transparent|none)\w+
这也关心注释行。您当前的正则表达式不排除任何东西。由于 PCRE 支持这些类型的结构,它应该受益于负前瞻。
您可以使用正数 lookahead with an alternation 而不是 {3,10}
您可以使用 +
来匹配一个字符一次或多次。
(^\s*background:\s*)(?!\b(?:none|transparent)\b)[a-z]+;
如果您不再指那个组,您也可以省略 (^\s*background:\s*)
周围的括号。