Multiple patterns search in Regex in python

enter image description here

import re
pattern1= r'\d+\s'
place = | 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:


    Sample script:

    inp = 'I saw it 2 mins ago'
    if ('\b\d+\s*(?:m|mins)\b', inp)):

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


    import re
    m ='\b\d+ ?m(?:ins)?\b', 'See you in 2 mins or sooner')
    if m:


    2 mins

    Python Demo