Home > Blockchain >  How to capture one of the two words using regex?
How to capture one of the two words using regex?

Time:02-16

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!

CodePudding user response:

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
  • Related