-1

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

1
  • Try re.search("|".join([pattern, pattern1]), s)? Commented Sep 14, 2020 at 5:28

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

1 Comment

I apologize for the DV. It was a mistake as I was going to UV, instead.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.