TransWikia.com

How to use "." as a wildcard inside "string" instead of pattern?

Stack Overflow Asked by miciobauciao on September 14, 2020

I have this:

incompleted_string1 = "Thom"
incompleted_string2 = "s Mueller naive"
entire_string = 'Thom.s Mueller naive'  # <= dot means any char!!! I dont know which char is it
pattern = "mas M"

I would like to know if "mas M" if present inside entire_string. I do not care if "." is equal to "a" or something else. I cannot change the pattern string!

re.findall("mas M", entire_string)

This returns [] I’d like to have "mas M" but True will be enough

Thank you for your help

2 Answers

The another approach could be to have all the possible combinations of pattern

bool(re.search(pattern  + "|"+ "|".join([pattern[0:i] + '.' + pattern[i+1:] for i in range(len(pattern))]), entire_string))

Answered by mad_ on September 14, 2020

You can replace each char in the pattern with [ + this char + . + ]:

bool(re.search("".join([f"[{x}.]" for x in pattern]), entire_string))

The pattern will look like [m.][a.][s.][ .][M.] here, and each can match either the corresponding letter or a dot. See the regex demo.

See the Python demo:

import re
incompleted_string1 = "Thom"
incompleted_string2 = "s Mueller naive"
entire_string = 'Thom.s Mueller naive'  # <= dot means any char!!! I dont know which char is it
pattern = "mas M"
print (bool(re.search("".join([f"[{x}.]" for x in pattern]), entire_string)) )
# => True

Answered by Wiktor Stribiżew on September 14, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP