Reputation: 1860
I want to remove trailing spaces of each line from a text file, keeping the line breaks intact. I am using Visual studio 2012's Regex feature for this.
When I am trying to find \s*\r?\n
and replace with \r\n
it is also stripping out all the empty lines, which is not expected.
Is there anything that I am missing?
Upvotes: 1
Views: 2223
Reputation: 457
I know this is old but i use the search and replace with regex of Visual Studio with this string (no quotes) " +\r?$" and leave the replace field empty then just do replace all. This preserves the line breaks and works for the VS regex flavor.
Upvotes: 2
Reputation: 75232
Set subtraction to the rescue!
[\s-[\n]]+\n
...or any whitespace character (\s
) except (-
) linefeed ([\n]
). Ordinarily, -
is treated as either a range operator or a literal hyphen (depending on its position within the character class), and [
is treated as a literal bracket. But if the hyphen is followed by something that looks like a character class, it becomes a set subtraction operator.
ref: Character Classes in Regular Expressions
Upvotes: 8
Reputation: 19423
Why are you trying to match the carriage return \r
and newline \n
if you don't want them replaced and then replace everything with \r\n
.
Instead match only the spaces and tabs and any other whitespace character that you want stripped and replace that with the empty string like this:
[ \t]*$
This will match zero or more spaces or tabs at the end of each line and replace them with the empty string.
NOTE: You will have to use multi-line mode so $
matches at the end of every line.
If you can't activate multi-line mode in VS then you can use another expression that doesn't need that:
[ \t]*(?=\r?\n)
This will match zero or more tabs and spaces as long as they are followed by an optional carriage return then a newline or in other words, as long as they are at the end of line.
Upvotes: 3