簡體   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