0

I want to find a match in string for the following pattern (field1)(field2)(field3)

field 1 can be either 'alpha' or 'beta' or 'gamma' field 2 is any number(can be whole number or decimal) field 3 is 'dollar' or 'sky' or 'eagle' or 'may'

Input string1 : "There is a string which contains alpha 2 sky as a part of it" Output1: alpha 2 sky

Input string2 : "This sentence contains a pattern beta 10.2 eagle" Output2: beta 10.2 eagle

I'm trying the following code but it's not flexible to include the multiple string matches together. value = " This sentence contains a pattern beta 10.2 eagle"

match = re.findall("beta \d.* dollar", value)
2
  • match = re.search("[beta | alpha | gamma]* \d.* [dollar | sky | eagle | may]*", value) something like this ? Commented May 19, 2021 at 3:34
  • @AkshayJain isn't [...] means character set? Commented May 19, 2021 at 3:39

1 Answer 1

1

You may use the following regex to collect all the relevant fields

  • (alpha|beta|gamma) : capture group - alternation with one of this words
  • \s+ : follow by 1+ whitespaces
  • ( : capture group
    • \d+ : 1+ digits, follow by
    • (?:\.\d+)? : (an optional) non-capturing group - literal '.' follow by 1+ digits
  • ) : close capture group
  • \s+ : follow by 1+ whitespaces
  • (dollar|sky|eagle|may) : capture group - alternation with one of this words
import re
regex = r'(alpha|beta|gamma)\s+(\d+(?:\.\d+)?)\s+(dollar|sky|eagle|may)'

s = '''
There is a string which contains alpha 2 sky as a part of it
This sentence contains a pattern beta 10.2 eagle
'''

match = re.finditer(regex, s)

for m in match:
     print(m.group(0))

# alpha 2 sky
# beta 10.2 eagle
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. This works ! Would be great if you could explain this, as I'm new to regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.