繁体   English   中英

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

[英]extract background color with regular expression

假设我们在元素上设置背景如下:

  1. 背景:绿色
  2. 背景:url(“ big_green.png”)
  3. 背景:绿色url(“ big_green”)不重传
  4. 背景:url(“ big_green”)绿色不重复

我想要的是提取背景色值,而不是url()中的值。

您可以使用 :

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

演示版

说明:(?: (?:background:\\s")非捕获组

background:匹配字符background:字面意义(区分大小写)

\\s匹配任何空格字符[\\r\\n\\t\\f ]

"相匹配的字符"从字面上

第一捕获组(.+)

.+匹配任何字符(换行符除外)

量词:一次至无限次,尽可能多次,并根据需要返回[贪婪]

(?:")非捕获组

"相匹配的字符"从字面上

在此处输入图片说明

我会去

background:\s"(.+)"

这样,您假设background后面只能有一个空格( \\s )和一个" 。如果urlbackground之后,并且您不需要任何前瞻,则它将不匹配。

演示@ regex101

编辑
根据您的第三个和第四个示例,上述正则表达式显然不起作用。

background:\s(?:"(.+)"|(?!url)(\w+)|url\(.+\) (.+?)\s)

这将匹配您所有的示例案例。

演示@ regex101

说明:

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