简体   繁体   中英

Multiple string match in regex Python

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM