简体   繁体   中英

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().

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM