Regular epxression (sass variables)

Altaula

New Member
#1
(Node.js) I have to match all Sass variables from file. But I can have variables and mixins in one file. I need to update regular epxression to not match a variables from mixin directive or from mixin / function content (nested).
So only:
  1. $test: true;
  2. $white: #fff !default;
  3. $sizes: (25: 0.25rem, 50: 0.5rem) !default;
Regular expression: /\$([^:]*)\s*:\s*([^;]*)\s*;/g
https://regex101.com/r/oRuWjS/1
Mã:
$test: true;

$white: #fff !default;

$sizes: (
  25: 0.25rem,
  50: 0.5rem
) !default;

@mixin parent ($first, $second: "") {
  .#{$first} {
    @content;
  }
}
 

Admin

Administrator
Thành viên BQT
#2
Using
Mã:
/@mixin[^(]*\([\s\S]*?^}$|\$([^:]*?)\s*:\s*([^;]*?)\s*;/gm
you may match from @mixin to the } that is alone on a line, and skip this match, else collect your other matches. See the regex demo.
Mã:
var s = "$test: true;\n\n$white: #fff !default;\n\n$sizes: (\n  25: 0.25rem,\n  50: \n0.5rem\n) !default;\n\n@mixin parent ($first, $second: \"\") {\n  .#{$first} {\n    \n@content;\n  }\n}\n";
var rx = /@mixin[^(]*\([\s\S]*?^}$|\$([^:]*?)\s*:\s*([^;]*?)\s*;/gm;
var m, res = [];
while (m=rx.exec(s)) {
   if (m[1]) {
       res.push([m[1], m[2]]);
   }
}
console.log(res);
Details

  • @mixin[^(]*\([\s\S]*?^}$ - the alternative that will be skipped:
    • @mixin - a literal substring
    • [^(]* - 0+ chars other than (
    • \( - a (
    • [\s\S]*? - any 0+ chars as few as possible
    • ^}$ - a } that is on a separate line
  • | - or
  • \$ - a $ char
  • ([^:]*?) - Group 1: 0+ chars other than : as few as possible
  • \s*:\s* - a : enclosed with 0+ whitespaces
  • ([^;]*?) - Group 2: 0+ chars other than : as few as possible
  • \s*; - 0+ whitespaces followed with ;.
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top