需要帮助使用正则表达式从 grid-template-columns css 字符串中查找每个 row/column css 属性

Need help for finding every row/column css property from grid-template-columns css string using regex

我正在构建一个需要行和列 CSS 解析器的应用程序。因此,我需要使用正则表达式和 return 数组提取 CSS 数据。

Css 字符串是: 1fr minmax(75px, auto) fit-content(40%) repeat(3, 200px) 200px repeat(auto-fill, 100px) 300px repeat(auto-fill, minmax(75px, auto))

数组输出需要: ["1fr", "minmax(75px, auto)", "fit-content(40%)", "repeat(3, 200px)", "200px", "repeat(auto-fill, 100px)", "300px", "repeat(auto-fill, minmax(75px, auto))"]

我试过了:

const getTotalColumnOrRowArray = (css_string) => {
    // abc123 ||OR|| abc-abc(abc123, abc123) ||OR|| abc
    let arr = css_string.match(/\d+[a-zA-Z\S]+|([a-zA-Z-\S]+\([a-zA-Z-\d\S]+, [a-zA-Z-\d\S]+\))|[a-zA-Z\S]+/g);
    return arr;
};

但是不能return"repeat(auto-fill, minmax(75px, auto))"这个值。

如果总有没有括号的部分先匹配,后面有可选的有括号的部分,它本身只能有一层嵌套:

[^\s()]+(?:\([^\s()]+(?:\([^()]+\))?(?:, *[^\s()]+(?:\([^()]+\))?)*\))?

部分

  • [^\s()]+ 匹配任何字符 1+ 次,除了 ( ) 或空白字符
  • (?:非捕获组
    • \( 匹配 (
    • [^\s()]+ 匹配任何字符 1+ 次,除了 ( ) 或空白字符
    • (?:非捕获组
      • \([^()]+\) 匹配 ( 1+ 次任何字符,除了 ( ) 或空白字符并匹配 )
    • )?关闭群组并使其可选
    • (?:非捕获组
      • , *[^\s()]+ 匹配逗号、可选空格和 1+ 次除 ( ) 或空白字符
      • 之外的任何字符
      • (?:\([^()]+\))? 像以前一样用括号匹配可选部分
    • )* 关闭群组并可选择重复
    • \) 匹配 )
  • )?关闭群组并使其可选

Regex demo

const s = "1fr minmax(75px, auto) fit-content(40%) repeat(3, 200px) 200px repeat(auto-fill, 100px) 300px repeat(auto-fill, minmax(75px, auto))";
const regex = /[^\s()]+(?:\([^\s()]+(?:\([^()]+\))?(?:, *[^\s()]+(?:\([^()]+\))?)*\))?/g;
let result = Array.from(s.matchAll(regex), m => m[0])
console.log(result);