Skip to content Skip to sidebar Skip to footer

Python Looping Through String And Matching It With With Wildcard Pattern

string1='abc' string2='abdabcdfg' I want to find if string1 is substring of string2. However, there are wildcard characters like '.' can be any letter, y can be 'a' or 'd', x can

Solution 1:

I know you are specifically asking for a solution using a loop. However, I would suppose a different approach: You can easily translate your pattern to a regular expression. This is a similar language for string patterns, just much more powerful. You can then use the re module to check whether that regular expression (and thus your substring pattern) can be found in the string.

def to_regex(pattern, table):
    # join substitutions from table, using c itself asdefaultreturn ''.join(table.get(c, c) for c in pattern)

import re
symbols = {'.': '[a-z]', '#': '[ad]', '+': '[bc]'}
print re.findall(to_regex('.+#', symbols), 'abdabcdfg')

If you prefer a more "hands-on" solution, you can use this, using loops.

deffind_matches(pattern, table, string):
    for i inrange(len(string) - len(pattern) + 1):
        # for each possible starting position, check the patternfor j, c inenumerate(pattern):
            if string[i+j] notin table.get(c, c):
                break# character does not matchelse:
            # loop completed without triggering the breakyield string[i : i + len(pattern)]

symbols = {'.': 'abcdefghijklmnopqrstuvwxyz', '#': 'ad', '+': 'bc'}
printlist(find_matches('.+#', symbols, 'abdabcdfg'))

Output in both cases is ['abd', 'bcd'], i.e. it can be found two times, using these substitutions.

Post a Comment for "Python Looping Through String And Matching It With With Wildcard Pattern"