Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to remove trailing whitespace and multiple blank lines

I'd like regex expressions to use in a Visual Studio 2013 extension written in C#.

I'm trying to remove trailing whitespaces from a line while preserving empty lines. I'd also like to remove multiple empty lines. The existing line endings should be preserved (generally carriage return line feed).

So the following text (spaces shown as underscores):

hello_world__


___hello_world_
__
__
hello_world

Would become:

hello_world

___hello_world

hello_world

I've tried a number of different patterns to remove the trailing spaces but I either end up not matching the trailing spaces or losing the carriage returns. I haven't yet tried to remove the multiple empty lines.

Here's a couple of the patterns I've tried so far:

\s+$

(?<=\S)\s+$
like image 242
sclarke81 Avatar asked Nov 28 '25 10:11

sclarke81


2 Answers

Thanks for the answers so far. None of them are quite right for what I need, but they've helped me come up with what I needed. I think the issue is that are some oddities with regex in VS2013 (see Using Regular Expressions in Visual Studio). These two operations work for me:

Replace \ +(?=(\n|\r?$)) with nothing.

Replace ^\r?$(\n|\r\n){2,} with \r\n.

like image 175
sclarke81 Avatar answered Nov 29 '25 23:11

sclarke81


To remove multiple blank lines and trailing whitespace with

(?:\r\n[\s-[\rn]]*){3,}

and replace with \r\n\r\n.

See demo

And to remove the remaining whitespace, you can use

(?m)[\s-[\r]]+\r?$

See demo 2

like image 41
Wiktor Stribiżew Avatar answered Nov 29 '25 23:11

Wiktor Stribiżew