Search string in string with wildcard char

Viewed 62

I was looking around regex and fnmatch threads but couldn't find similar problem.

User enters some string and I need to find it in string that is in col in dataframe. Strings have N char as a wildcard so N can be one of 3 other letters B W C

'BBBB' in 'BBNBAQWE' = True

becouse N transformed into B

'QWER' in 'QNERVFRZ' = True

becouse N transformed into W

strings can be diffrent sizes and from my understanding only one N letter can be morphed in that string to fit user request

What im planning is to add True/False value to new col based on output

df['is_present'] = df['strings'].map(lambda x: get_strings(x, user_val))
1 Answers

One way is to replace every letter of searched pattern allowing 'N' as alternative.

You can switch all the patterns using list comprehension:

raw_pattern = 'QWER'
pattern = ''.join(['(?:' + letter + '|N)' for letter in list(raw_pattern)])
#pattern = '(?:Q|N)(?:W|N)(?:E|N)(?:R|N)' 

Then

sentence = 'QNENVFRZ'
re.findall(pattern, sentence)
>>> ['QNEN']

If the resulting list is not empty, the pattern was found in the sentence.

Edit: The question was modified to only accept 'N' if it exchanges 'B', 'W', or 'C'. Then we would like to create pattern like this:

pattern = ''.join(['(?:' + letter + '|N)' if letter in ('B', 'W', 'C') else letter for letter in list(raw_pattern)])
# pattern = 'Q(?:W|N)ER'

Of course then the original example does not match, as R was not able to replace N. We get:

re.findall(pattern, sentence)
>>> []

We can check whether something was matched comparing to an empty list.

re.findall(pattern, sentence) == []
>>> True
Related