suresh_chinthy
suresh_chinthy

Reputation: 377

Find a list of words using regular expression

I am going to find a match like below. Just explained using words. ComanyCode + dot + [4 Digit Number]

Some Examples as follows US.1234, UK.4321 etc

import re

txt = "TheUS.8888 in S8ain"

I am trying to use an array of input parameters.

Below is how I approached this. Can someone suggest me the correct way.

Companys = ['UK','CA','GE''US']  


for k in Companys:
    x = re.findall("k.\d\d\d\d", txt)

Ideally from above sample code US.8888 should be returned.

Upvotes: 0

Views: 39

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

I would use re.findall here with an alternation:

txt = "TheUS.8888 in S8ain"
countries = ['UK', 'CA', 'GE', 'US']
regex = r'(?:' + '|'.join(countries) + r')\.\d{4}'
print(regex)    # (?:UK|CA|GE|US)\.\d{4}
matches = re.findall(regex, txt)
print(matches)  # ['US.8888']

Upvotes: 5

Related Questions