Convert a TRIM on regex

Viewed 26

I have a large string and one of the lines is in the form of

Description:          something here....

I want to get everything in the: something here... without any trailing or leading space on it. Currently I'm doing it with a mix of regex and a strip(). How could this be done entirely in regex? Currently:

re.search('Description:\s+(.+)', body).group(1).strip()

Other thoughts:

re.search('Description:\s+\w(.+)\w', body).group(1) # works

Also, why doesn't putting an anchor work in the above context?

re.search('Description:\s+\w(.+)$', body).group(1) # fails
1 Answers

You can use either of

Description:\s+(.*\S)

See the regex demo.

The point is that you need to match up to the last non-whitespace character. .* matches any zero or more characters other than line break chars, as many as possible, so the \S matches the last non-whitespace character in the string.

If you have a multiline string and you need to get to the last non-whitespace character, you may add re.S / re.DOTALL option when passing the pattern above to a regex method, or re-write it as

Description:\s+(\S+(?:\s+\S+)*)

where \S+ matches one or more non-whitespace chars and (?:\s+\S+)* matches zero or more occurrences of one or more whitespaces followed with one or more non-whitespace chars.

See this regex demo.

Related