K Max
K Max

Reputation: 102

matching a group of words by regex in python

I'm trying to change:

'1foo 1.5f/b 1 Foo Bar'

to:

"1fb 1.5fb 1fb"

this is my code:

re.sub(r"(?i)\b(\d+\.*\d*)\s*(f\/b|foo|foo bar)\b",r"\1fb",'1foo 1.5f/b 1 Foo Bar')

but what I get is:

'1fb 1.5fb 1fb Bar'

This is because both foo and foo bar are in the match group. How can I avoid Bar being in the output?

Thanks in advance

Upvotes: 1

Views: 58

Answers (2)

papanito
papanito

Reputation: 2574

You can also switch foo and foo bar i.e. foo|foo bar would be foo bar|foo

re.sub(r"(?i)\b(\d+\.*\d*)\s*(f\/b|foo bar|foo)\b",r"\1fb",'1foo 1.5f/b 1 Foo Bar')

Output:

1fb 1.5fb 1fb

Upvotes: 0

anubhava
anubhava

Reputation: 784878

You can match using this regex:

(?i)(\d*\.?\d+)\s*(?:f/b|foo(?: bar)?)\b

And replace using \1fb

RegEx Demo

Code:

import re

s = '1foo 1.5f/b 1 Foo Bar'

r = re.sub(r'(?i)(\d*\.?\d+)\s*(?:f/b|foo(?: bar)?)\b', r'\1fb', s)

Output:

1fb 1.5fb 1fb

Upvotes: 2

Related Questions