jason
jason

Reputation: 1631

extract background color with regular expression

Suppose we set background on an element as following:

  1. background: green
  2. background: url("big_green.png")
  3. background: green url("big_green") no-repat
  4. background: url("big_green") green no-repeat

What I want is to extract the background-color value, not the value in the url().

Upvotes: 0

Views: 928

Answers (2)

KeyNone
KeyNone

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.

Demo @ regex101

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.

Demo @ regex101

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

Sujith PS
Sujith PS

Reputation: 4864

You can use :

 (?:background:\s")(.+)(?:")

Demo

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

enter image description here

Upvotes: 2

Related Questions