0

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.

5
  • Why not use regular expressions as patterns, especially since you already tagged them? Commented Apr 5, 2020 at 8:07
  • Just put \S+ or \w+ instead of *** Commented Apr 5, 2020 at 8:11
  • How do I create this dynamically? since the list contains multiple patterns Commented Apr 5, 2020 at 8:16
  • You either must have a closed set of patterns or a rule to generate them. Commented Apr 5, 2020 at 8:21
  • I understood Binh's logic and accepted his answer, however he went too strict with the data and matched exactly what I wanted , so if I try to name my pc "asm-1.2" the validation fails because he is only matching [a-zA-Z] , I tried \w and didnt get a match as well. How can I match any word with special characters as well? Commented Apr 5, 2020 at 8:39

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

6 Comments

oh, so your suggesting me to replace the *** with the regex expressions, I understand, thanks a lot
what does the 'f' do in re.match?
the f allows you to put a variable inside a string. Ex: x=5 and you can print(f'your value is {x}') ==> your value is 5. In the answer above, {item} is a string in list, ex: item = 'The Computer name is [a-zA-Z]+? and its RAM is \d+[gbGB]+' at 1st iteration in for loop
[^ ] will match anything except space
|

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.