Reputation: 1187
I am trying to make a script that reads the list element sequentially and concatenate them each into regex pattern.
for example,
I have a list like this:
lst = ['B.', 'Article', 'III']
And want to comprise regex something like this:
re.search(r lst[0]\s+lst[1]\s+lst[2]).group()
so that it can match below regardless of white_spaces between each elements from the list:
candidate_1 = 'B. Article III'
candidate_2 = 'B. Article III'
Upvotes: 0
Views: 47
Reputation: 168616
Try str.join()
, like so:
r'\s+'.join(lst)
Here is a complete program:
import re
def list2pattern(l):
return r'\s+'.join(l)
lst = ['B.', 'Article', 'III']
assert re.search(list2pattern(lst), 'B. Article III')
assert re.search(list2pattern(lst), 'B. Article III')
assert not re.search(list2pattern(lst), 'B.Article III')
assert not re.search(list2pattern(lst), 'George')
Upvotes: 3