簡體   English   中英

如何使用正則表達式對具有樣式的對象進行分組?

[英]How to group a object with styles using regular expressions?

我有一個字符串

" 'backgroundColor': someVaraible,
  'border': '1px solid red',
  'line-height': 1,
  'background-color': 'rgba(142, 27, 95, 1)' "

如何使用Regexp獲取字符串數組?

[
  "'backgroundColor': someVaraible",
  "'border': '1px solid red'",
  "'line-height': 1",
  "'background-color': 'rgba(142, 27, 95, 1)'"
 ]

最簡單的方法就是使用String.split()。 在您的情況下,只需使用“,”作為分隔符。 https://www.w3schools.com/jsref/jsref_split.asp

您可以使用帶有正則表達式的split來查找不在括號之間的逗號(這是一個負向前瞻)。

/,(?![^(]+\))/

 let items = "'backgroundColor': someVaraible, 'border': '1px solid red', 'line-height': 1, 'background-color': 'rgba(142, 27, 95, 1)'" console.log( // Split on commas not between parentheses items.split(/,(?![^(]+\\))/) // Do some cleanup on the strings // trim() -> trim the trailing whitespace .map(i=>i.trim()) ) 

也許你只是想做一些松散的字符串匹配而不支持所有的CSS語法。 在您的示例中,您可以通過換行符拆分字符串:

var items = str.split(/\r?\n/);

解析所有有效的CSS語法將非常復雜。 在瀏覽器中,您可以使用內置的CSS解析器來提取單個規則:

var doc = document.implementation.createHTMLDocument(''),
    style = document.createElement('style');
style.textContent = '.myClass {color: #000;}';
doc.body.appendChild(style);
console.log(style.sheet.cssRules);  // List of CSS rules

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM