简体   繁体   English

使用正则表达式提取背景色

[英]extract background color with regular expression

Suppose we set background on an element as following: 假设我们在元素上设置背景如下:

  1. background: green 背景:绿色
  2. background: url("big_green.png") 背景:url(“ big_green.png”)
  3. background: green url("big_green") no-repat 背景:绿色url(“ big_green”)不重传
  4. background: url("big_green") green no-repeat 背景:url(“ big_green”)绿色不重复

What I want is to extract the background-color value, not the value in the url(). 我想要的是提取背景色值,而不是url()中的值。

You can use : 您可以使用 :

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

Demo 演示版

Explanation : (?:background:\\s") Non-capturing group 说明:(?: (?:background:\\s")非捕获组

background: matches the characters background: literally (case sensitive) background:匹配字符background:字面意义(区分大小写)

\\s match any white space character [\\r\\n\\t\\f ] \\s匹配任何空格字符[\\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. 这样,您假设background后面只能有一个空格( \\s )和一个" 。如果urlbackground之后,并且您不需要任何前瞻,则它将不匹配。

Demo @ regex101 演示@ 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 演示@ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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