I'm trying to do a regex replace in Notepad++. Regex isn't my forte, but I thought I'd figured it out. I'm trying to match commas followed by any number of spaces, but only if the line ends with a "{". I want to replace these commas and any spaces that follow with ",\r\n" (a comma followed by a new line).
The purpose is to put each selector in a multi-selector group on new lines to make it easier to read. So given the following example:
.messageBox label, .messageBox a, .messageBox li {
font-size: 0.8em;
font-family: "Segoe UI",Arial,sans-serif;
}
should become
.messageBox label,
.messageBox a,
.messageBox li {
font-size: 0.8em;
font-family: "Segoe UI",Arial,sans-serif;
}
Notice how the selector line has it's commas replaced with ,\r\n but the font-family style does not. That's the purpose of looking for lines that end in "{".
This is the regex I have currently come up with:
(, *)(?=.*\{$)
which appears to work as expected in the regexr editor. It finds the commas in the selector line, but not the commas in the font-family line. However, notepad++ finds the commas in both. What am I doing wrong? I have checked the "matches newline" checkbox in Notepad++ which should enabled the /m (multiline) flag.
Try with (?<=,)\s+(?=.*{$)
and use just \r\n
as replacement. I tested it with Notepad++ v8.4.8 and it worked like a charm.
Tick the "Wrap around" checkbox to get a result independent of the current cursor position (otherwise only matches after the cursor position are replaced). Ensure that you select the "Regular Expression" search mode.
The regular expression means:
Search one or more whitespaces (\s+
) that are prefixed with a comma ((?<=,)
) and followed by any amount of any characters, an opening brace and a line ending ((?=.*{$)
). With this expression, the match is only the whitespace(s), so you don't need to back reference any part of the match.