How to match anything except two or more consecutive spaces in a regex?
I have a test string like
string = ' a title of foo b '
I would like to capture title of foo from string. Basically, this means that we start with any number of spaces, followed by a combination of letters and spaces, but never more than one consecutive space, and then again by any number of spaces.
Attempt (in python).
string = ' title of foo '
match = re.match('\s*([^\s{2,}])*\s*', string)
This doesn't work because the square brackets need a list, I think.
You can use this lookahead based regex:
>>> string = ' a title of foo b '
>>> print re.search(r'\S+(?:(?!\s{2}).)+', string).group()
title of foo
RegEx Demo
It would be easier to just use:
stripped_string = string.strip()
The function strip() removes the whitespace from the start and end of a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With