John
John

Reputation: 1039

vim regex - match any number of whitespace at end of line except 2

I want to write a fixer for ale to remove all whitespace at the end of a line except for a double whitespace - in markdown this is used to create a linebreak.

I need to match "at end of row, 1 or more white space AND not 2 white space"

kind of like \s\+$\&\s\{^2}$ except that ^ is not negation inside curly brackets. Some googling reveals that negating a count of a meta character seems to be a particularly niche problem.

Upvotes: 2

Views: 948

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627190

You can use

:%s/\v(\s)@<!\s(\s{2,})?$//g

Details

  • % - search on all lines
  • s - substitute
  • \v - very magic mode
  • (\s)@<! - location not immediately preced with a whitespace
  • \s - a whitespace
  • (\s{2,})? - an optional occurrence of two or more whitespaces
  • $ - end of line
  • g - all occurrences on the line.

This is how this regex works (translated into PCRE).

Upvotes: 2

romainl
romainl

Reputation: 196777

(This really should be a comment but formatting is important, here)

How do you want the following snippet to look after you have "fixed" it (spaces marked with _)?

First line, without trailing spaces
Second line, with one trailing space_
Third line, with two trailing spaces__
Fourth line, with more than two trailing spaces______

Upvotes: 0

Related Questions