skip to Main Content

I need a regex to change this:

.my-class {
  @apply .p-4 .bg-red-500;
}

into this:

.my-class {
  @apply p-4 bg-red-500;
}

I found this regex but it is not working:

(?<=@apply.*).

any ideas?

2

Answers


  1. Chosen as BEST ANSWER

    Managed to change all sass files in a directory like this:

    <?php
    foreach(glob('./site/assets/stylesheets/' . sprintf("**/*.%s", 'sass')) as $file) {
      $contents = file_get_contents($file);
      $regex = '/((?:G(?!^)|@apply)[^.rn]*)./m';
      $subst = '$1';
    
      $result = preg_replace($regex, $subst, $contents);
    
      file_put_contents($file, $result);
      echo "written $file";
    }
    

  2. Your regex will work in .NET or Python PyPi regex module or JavaScript ECMAScript 2018+ compliant environments that support infinite-width lookbehind patterns.

    If it is PCRE/Java/Ruby, you can use

    ((?:G(?!^)|@apply)[^.rn]*).
    

    And replace with $1 backreference to Group 1. See the regex demo. I assumed you want to find dots on the same line as @apply, so I added r and n to the negated character class, if it is not so, remove r and n.

    Details:

    • ((?:G(?!^)|@apply)[^.rn]*) – Group 1: either the end of the previous successful match (G(?!^)) or @apply and then zero or more chars other than a dot, CR and LF chars
    • . – a dot
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search