dimanche 5 décembre 2021

match different message patterns from a user input in Python

I'm trying to match a message from a user input that follows a certain pattern. 1st pattern is a keyword 'data' followed by two digits, and the 2nd is the keyword 'status' followed by a word. I used if statements and it works only if there is a single pattern to be matched but not both as the second pattern would be skipped.

import re


message = input('Enter Your Message?\n')



trainee_data_pattern = re.compile(r"^(data)?\s?(\d\d)$")
data_match = trainee_data_pattern.search(message)
trainee_status_pattern = re.compile(r"^(status)?\s?(\w+)$")
status_match = trainee_status_pattern.search(message)

try:
    if data_match.group() == message:
        matched_num = trainee_data_pattern.search(message).group(2)
        
        list1 = [11,22,33]
        if int(matched_num) in list1:
            print(f"ID: {matched_num}")
                
        else:
            print('no data')
        
    elif status_match.group() == message:  
    
        matched_status = trainee_status_pattern.search(message).group(2)
        
        list2 = ['good','bad','refurbished']
        if matched_status in list2:
            print(f"the status is {matched_status}")
                
        else:
            print('no data')
            
except AttributeError:
      res = trainee_data_pattern.search(message) 
      print('wrong pattern')

The desired functionality of the program is when a user inputs: data 22 -> ID: 22

status good -> the status is good

data 133 -> wrong pattern

Aucun commentaire:

Enregistrer un commentaire