Swifty
Swifty

Reputation: 71

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.

Upvotes: 2

Views: 89

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

In the Syntax Coloring Scheme Editor, use the following regex, making sure that the "Dot all" checkbox is unchecked:

--.*?(?=[^\r\n\S]*$)

Explanation:

--           # Match --
.*?          # Match any number of non-linebreak characters, as few as possible,
(?=          # until the following can be matched from the current position:
 [^\r\n\S]*  # Any number of whitespace characters except newlines
 $           # followed by the end of the line.
)            # End of lookahead

[^\S] is the same as \s, but the negated character class allows you to exclude certain characters from the class of allowed whitespace characters - in this case, newlines.

Upvotes: 0

melpomene
melpomene

Reputation: 85767

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).

Upvotes: 2

Related Questions