Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to capture one of the two words using regex?

I have these 4 regexes

1) \w+\s\\bmillion\\b 
2) \w+\s\\bmillions\\b 
3) \w+\s\\bbillion\\b 
4) \w+\s\\bbillions\\b 

How can i combine them together I tried () and [] but because of \b seems it does not work properly? TIA!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can combine them using a character class for [mb] and an optional s at the end.

As the \s is mandatory in the pattern, you can omit the first word boundary.

\w+\s[mb]illions?\b

Regex demo

Example

import re

pattern = r"\w+\s[mb]illions?\b"
strings = ["a million", "a millions", "a billion", "a billions", "a millionx", "a millionsx", "a billionx", "a billionsx"]


for s in strings:
    m = re.search(pattern, s)
    if m:
        print(m.group())

Output

a million
a millions
a billion
a billions
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading