'matching multiple parts of string with wildcards added

What I want with python to match a string with a substring, in the substring there are wildcards added, I tried this without luck, it works only without wildcards added in the Bstring and is exactly the same as the Astring:

import re
Astring = ['123.456.789.10.11.12.abc']
Bstring = ['*.456.789.*.11.12.*']
                                                                                                                                                                                                             
if re.findall(Astring, Bstring)):
    # (do something) 


Solution 1:[1]

One way of doing it(assuming you have two equal length lists, one for actual strings, one for wildcards):

import re

Astring = ["123.456.789.10.11.12.abc"]
Bstring = ["*.456.789.*.11.12.*"]

for string, pattern in zip(Astring, Bstring):
    pattern = pattern.replace(".", r"\.").replace("*", ".*")
    print(pattern)
    if re.fullmatch(pattern, string):
        print("It's OK")

output:

.*\.456\.789\..*\.11\.12\..*
It's OK

I had to first escape every dots into \. to match exactly a "dot" not "any character". Then I changed * to .* because .* means any character with any number of occurrences(start from zero).


Another simple way is using fnmath:

from fnmatch import fnmatch

Astring = ["123.456.789.10.11.12.abc"]
Bstring = ["*.456.789.*.11.12.*"]

for string, pattern in zip(Astring, Bstring):
    if fnmatch(string, pattern):
        print("It's OK")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1