Search code examples
regexeditpad

Using regex to trim trailing white space


My editor EditpadPro allows me to create syntax colouring schemes. The scheme I'm writing includes comments which span "--" to end of a line.

I'd like a regex which starts from the "--" but which stops at the last non-blank character. I cannot use "replace" as I'm just entering the regex, not using it myself.

So, if the text in my line of code is:

X=1 -- This is a comment with trailing blanks

Then the regex would return:

-- This is a comment with trailing blanks

The reason for this is that I can highlight the trailing blank space as waste space.


Solution

  • I'm not familiar with EditPad Pro, but

    --(?:.*\S)?
    

    might work.

    The idea is to match --, followed by 0 or more of any (non-newline) character (.), followed by a non-space character (\S). Because the "0 or more" part is greedy, it will try to match as much of the line as possible, thus making \S match the last non-blank character of the line.

    The ? makes the whole thing after -- optional. This is because you might have a comment without a non-space character in it:

    --
    

    This should still be matched as a comment, but not any trailing spaces (if any).