Home > Mobile >  How to add list of words inside particular regex
How to add list of words inside particular regex

Time:11-25

import re
pg_content = "Hello my Ref No: 9XD123D and his Buyer's Ref: 87CVX61"
ref_no = re.findall(r"(?:(?<=Buyer's Ref: )|(?<=Ref No: )|(?<=Ref No : ))[\w\d-] ",pg_content)
print(ref_no)

I want to run the script by adding list = ["Buyer's Ref:","Ref No:","Ref No :"] instead of adding "|" to the re.findall line. Is there any solution. Just need to insert all items in the list to re.findall

CodePudding user response:

Using re.findall we can try:

pg_content = "Hello my Ref No: 9XD123D and his Buyer's Ref: 87CVX61 and another Ref No : ABC123"
terms = ["Ref No ", "Ref No", "Buyer's Ref"]
regex = r'\b(?:'   r'|'.join(terms)   r'): (\S )'
output = re.findall(regex, pg_content)
print(output)  # ['9XD123D', '87CVX61', 'ABC123']
  • Related