Home > Software engineering >  regex to delete all dots in a line starting with specific word
regex to delete all dots in a line starting with specific word

Time:11-18

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?

CodePudding user response:

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)[^.\r\n]*)\.

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)[^.\r\n]*) - 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

CodePudding user response:

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)[^.\r\n]*)\./m';
  $subst = '$1';

  $result = preg_replace($regex, $subst, $contents);

  file_put_contents($file, $result);
  echo "written $file";
}
  • Related