Search code examples
cssregexsassregexp-replace

How can I use regex find-and-replace to insert missing spaces before curly braces?


I have an SCSS file, for example:

.nice{
  display: flex;

  &--green {
    color: green;
  }

  &--2{
    display: grid;
  }

  @media only screen and (max-width: 600px){
    display: none;
  }
}

I would like to insert a space before opening curly braces where the space is missing. How can I do it using regex find-and-replace?


Solution

  • Even in the cases where we have nested &, it will always be followed by at least 1 letter, number, hyphen or underscore, as per CSS grammar. We also need to consider media queries, in which case it will be a ) before the { character.

    So, I believe this should cover all cases:

    Replace: ([a-zA-Z0-9-_\)]+)(\s*)(\{)
    With: $1 $3
    (Where $1 represents the first matching group, etc.)