In: Computer Science
You are given a task to parse through financial information and find the word “money” followed by “bad” 2 or more times or “money” followed by “good” once. Create a regex that can search achieve this. You can ignore spaces. Legal words in the language could be “moneybadbadbad” or “moneygood”
The following is the code for above question. Here we used regex to solve the problem
import re
#input text to search for example
txt1="he is a moneybadbadbad boy"
txt2="he is a moneybad boy"
txt3="he is a moneygoodgood boy"
txt4="he is a moneygood boy"
#the word boundary \b is used for moneygood to match exactly once and badbad+ is used to match bad more than 2 times
x1=re.search(r'(\bmoneygood\b)|((money{1})badbad+)',txt1)
x2=re.search(r'(\bmoneygood\b)|((money{1})badbad+)',txt2)
x3=re.search(r'(\bmoneygood\b)|((money{1})badbad+)',txt3)
x4=re.search(r'(\bmoneygood\b)|((money{1})badbad+)',txt4)
#print and test all matches
print(x1)
print(x2)
print(x3)
print(x4)
I am also attaching the output and code screenshot for your reference.
Output and code screenshot:
#Please don't forget to upvote if you find the solution
helpful. Feel free to ask doubts if any, in the comments section.
Thank you.