asmij kun
asmij kun

Reputation: 25

Regex to dynamically find pattern - Python

I have a Python list which looks like below, I would like to build a regex to validate if my input strings match the list format.

list = ['The Computer name is *** and its RAM is ***','The Laptop is from *** Brand','The Laptop has windows ***/']

So the Python list has a collection of Strings, along with the following special set of characters: * = Match one word */ = Match one or more words

rest of the words in the list should be an exact match.

So basically I need to loop through the list, and compare it with an input String to see if my input string matches the format in the list.

For eg: I need to compare string a to list item 0, the string would be "The Computer name is Dell and its RAM is 2gb" this string would pass the validation. Whereas the following string would fail the validation "The Computer name is Dell and its RAM is 2 gb" because "2 gb" is 2 words and in our validation list we are expecting one word.

Upvotes: 0

Views: 835

Answers (1)

Binh
Binh

Reputation: 1173

So your list should be:

list = ['The Computer name is [a-zA-Z]+? and its RAM is \d+[gbGB]+', 'The Laptop is from [a-zA-Z]+? Brand', 'The Laptop has windows [a-zA-Z ]+?']
text = input('type someting: ')
for item in list:
    if re.match(f'{item}', text):
        #do something

Upvotes: 1

Related Questions