Reputation: 1631
Suppose we set background on an element as following:
What I want is to extract the background-color value, not the value in the url().
Upvotes: 0
Views: 928
Reputation: 9150
I'd go for
background:\s"(.+)"
This way you suppose there can be only a whitespace (\s
) and a "
after the background
. It won't match if url
comes after background
and you don't need any lookaheads for this.
EDIT
According to your third and fourth example the regex above obviously won't work.
background:\s(?:"(.+)"|(?!url)(\w+)|url\(.+\) (.+?)\s)
This one will match all your example cases.
Explanation:
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
Upvotes: 1
Reputation: 4864
You can use :
(?:background:\s")(.+)(?:")
Explanation :
(?:background:\s")
Non-capturing group
background:
matches the characters background: literally (case sensitive)
\s
match any white space character [\r\n\t\f ]
"
matches the character "
literally
1st Capturing group (.+)
.+
matches any character (except newline)
Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
(?:")
Non-capturing group
"
matches the character "
literally
Upvotes: 2