如何使用正则表达式对具有样式的对象进行分组?

问题描述 投票:1回答:3

我有一个字符串

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

如何使用Regex获取字符串数组?

[
  "'backgroundColor': someVaraible",
  "'border': '1px solid red'",
  "'line-height': 1",
  "'background-color': 'rgba(142, 27, 95, 1)'"
 ]
javascript regex
3个回答
1
投票

您可以使用带有正则表达式的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())
)

1
投票

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


1
投票

也许你只是想做一些松散的字符串匹配而不支持所有的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
© www.soinside.com 2019 - 2024. All rights reserved.