snapper
snapper

Reputation: 1187

Regex Pattern Comprising From the Elements in List

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

Answers (1)

Robᵩ
Robᵩ

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

Related Questions