Regex to match all trailing whitespace _and_ newlines.

Peter Otten __peter__ at web.de
Thu Sep 1 06:30:15 EDT 2011


Dotan Cohen wrote:

> In the terrific Anki [1] application I am trying to remove trailing
> whitespace from form fields. This is my regex:
> [\n+\s+]$

My attempt:

>>> sub = re.compile(r"\s*?(\n|$)").sub
>>> sub("<EOL>", "alpha   \nbeta   \r\n\ngamma\n")
'alpha<EOL>beta<EOL><EOL>gamma<EOL>'
>>> sub("<EOL>", "alpha   \nbeta   \r\n\ngamma")
'alpha<EOL>beta<EOL><EOL>gamma<EOL>'
>>> sub("<EOL>", "alpha   \nbeta   \r\n\ngamma\t")
'alpha<EOL>beta<EOL><EOL>gamma<EOL>'




More information about the Python-list mailing list