[英]extract background color with regular expression
假设我们在元素上设置背景如下:
我想要的是提取背景色值,而不是url()中的值。
您可以使用 :
(?:background:\s")(.+)(?:")
说明:(?: (?:background:\\s")
非捕获组
background:
匹配字符background:字面意义(区分大小写)
\\s
匹配任何空格字符[\\r\\n\\t\\f ]
"
相匹配的字符"
从字面上
第一捕获组(.+)
.+
匹配任何字符(换行符除外)
量词:一次至无限次,尽可能多次,并根据需要返回[贪婪]
(?:")
非捕获组
"
相匹配的字符"
从字面上
我会去
background:\s"(.+)"
这样,您假设background
后面只能有一个空格( \\s
)和一个"
。如果url
在background
之后,并且您不需要任何前瞻,则它将不匹配。
编辑
根据您的第三个和第四个示例,上述正则表达式显然不起作用。
background:\s(?:"(.+)"|(?!url)(\w+)|url\(.+\) (.+?)\s)
这将匹配您所有的示例案例。
说明:
background:\s #matches "background: " literally
(?: #start of non-capturing group
"(.+)" #matches characters enclodes by "" (Example 1)
| #OR
(?!url) #negative lookahead: if "url" comes afterwards, this isn't a match
(\w+) #matches mupltiple characters (Example 3)
| #OR
url\( #matches "url(" literally
.+ #matches multiple characters
\) #matches ") " literally
(.+?)\s #matches multiple characters until the next whitespace (Example 4)
) #end of non-capturing group
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.