ellgon
ellgon

Reputation: 23

Python Regular expression to remove blanks before and after a string

I'm buildin a tiny python program and I can't find the correct regex. Let me explain myself:

I have the next string

bar = '    Type of network         : Infrastructure'

And with de following code:

foo = re.findall(r'(\w+(\s\w+)+)\s+:\s+(\w+)', bar)
print(foo)

I obtain:

[('Type of network', ' network', 'Infrastructure')]

And I would like:

[('Type of network', 'Infrastructure')]

I know that I could do that splitting the string by ':' and trimming blanks, but I prefer the regex.

Thanks a lot

Upvotes: 0

Views: 97

Answers (3)

James Sapam
James Sapam

Reputation: 16940

Just another solution without using regex [ x.strip() for x in bar.split(':')]

Output: ['Type of network', 'Infrastructure']

Upvotes: 2

wypieprz
wypieprz

Reputation: 8219

How about the following one?

foo = re.findall(r'\s*(.*?)(?:\s*:\s*)(.+)(?<!\s)', bar)

It also handles strings like:

'    Type of network         : Infra structure  '

Upvotes: 0

Garrappachc
Garrappachc

Reputation: 749

Maybe you want to use non-capturing brackets:

(\w+(?:\s\w+)+)\s+:\s+(\w+)

Upvotes: 0

Related Questions