[英]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.