Reputation: 69
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)
Upvotes: 0
Views: 82
Reputation: 3989
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 wordsimport 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
Upvotes: 1