Multiple patterns search in Regex in python

enter image description here

import re
pattern=r'\d+'
pattern1= r'\d+\s'
place = re.search((pattern | pattern1),s)

I need this regex to work for s='2m' as well as s='2 m' so that I can find m and separate it also it should for in case of s='2 mins' or s= '2mins'

can someone please help me with this. Also PFA Thanks

2 answers

  • answered 2020-09-14 05:28 Tim Biegeleisen

    Just use a single pattern with an alternation:

    \b\d+\s*(?:m|mins)\b
    

    Sample script:

    inp = 'I saw it 2 mins ago'
    if (re.search(r'\b\d+\s*(?:m|mins)\b', inp)):
        print("MATCH")
    

  • answered 2020-09-14 12:28 Booboo

    Use the following pattern that does not use alternation but rather optional sub-expressions:

    \b\d+ ?m(?:ins)?\b
    

    Regex Demo

    1. \b Asserts position at a word boundary.
    2. \d+ matches 1 or more digits.
    3. ? Optional space. If you want to allow multiple spaces, then use *.
    4. m Matches 'm'.
    5. (?:ins)? Matches optional 'ins' in a non-capturing group.
    6. \b Asserts position at a word boundary.

    Use:

    import re
    
    m = re.search(r'\b\d+ ?m(?:ins)?\b', 'See you in 2 mins or sooner')
    if m:
        print(m[0])
    

    Prints:

    2 mins
    

    Python Demo