Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match anything except two or more consecutive spaces in a regex?

Tags:

python

regex

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.

like image 739
coneyhelixlake Avatar asked Dec 05 '25 11:12

coneyhelixlake


2 Answers

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

like image 117
anubhava Avatar answered Dec 06 '25 23:12

anubhava


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.

like image 37
gtlambert Avatar answered Dec 07 '25 00:12

gtlambert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!