Search for pattern in string in python

Question: I am very new to python, so please bear with me. This is homework I need help with.

So, for the matchPat function, I need to write a function that will take two arguments: str1 and str2 and return a boolean value indicating whether str1 is in str2. But I have to use an asterisk as a wild card in str1. * Can only be used in str1, and it will represent one or more characters that I need to ignore. MatchPat examples are as follows:

matchPat ('a * t * r', 'anteaters'): True

matchPat ('a * t * r', 'albatross'): True

matchPat ('a * t * r', 'artist'): False

My current matchPat function can determine if str1 characters are in str2, but I really don't know how I could tell python (using * as a wild card) to search for "a" (first letter) and after it finds a , skip the next 0 or more characters until you find the next letter (which will be "t" in the example), etc.

def matchPat(str1,str2):
    ## str(*)==str(=>1)
    if str1=='':
        return True
    elif str2=='':
        return False
    elif str1[0]==str2[0]:
        return matchPat(str1[2],str2[len(str1)-1])
    else: return True
+4
source share
5 answers

The main idea here is to compare each character in str1 and str2, and if the char in str1 is "*", find that character in str2, which is the character next to the "*" in str1.

, - ( find(), ), ( , , , ) -

def matchPat(str1, str2):
    index1 = 0
    index2 = 0
    while index1 < len(str1):
        c = str1[index1]
        #Check if the str2 has run it course.
        if index2 >= len(str2):
            #This needs to be checked,assuming matchPatch("*", "") to be true
            if(len(str2) == 0 and str1 == "*"):
                return True
            return False
        #If c is not "*", then it normal comparision.
        if c != "*":
            if c != str2[index2]:
                 return False
            index2 += 1
        #If c is "*", then you need to increment str1,
        #search for the next value in str2,
        #and update index2
        else:
            index1 += 1
            if(index1 == len(str1)):
                return True       
            c = str1[index1]
            #Search the character in str2
            i = str2.find(c, index2)
            #If search fails, return False
            if(i == -1):
                return False
            index2 = i + 1
        index1 += 1
    return True

OUTPUT -

print matchPat("abcde", "abcd")
#False
print matchPat("a", "")
#False
print matchPat("", "a")
#True
print matchPat("", "")
#True
print matchPat("abc", "abc")
#True
print matchPat("ab*cd", "abacacd")
#False
print matchPat("ab*cd", "abaascd")
#True
print matchPat ('a*t*r', 'anteater')
#True
print matchPat ('a*t*r', 'albatross')
#True
print matchPat ('a*t*r', 'artist')
#False
0

Python in; , str1 str2 str1 in str2.

split . "a*b*c".split("*") - ["a","b","c"].

, find.

, :

  • ,
  • ?

, , , . !

+2

find() , , ( ), -1, . index() , , .

, "*". , . , find() index() .

, , . , . - , .

, , , .

+1

, str1 '*'. str1 "" str2 " ", .

needles = needle.split('*')

( i) 0. haystack [i:] .

:

needles = needle.split('*')
i = 0
loop through all strings in needles:
    if current needle not in haystack[i:], return false
    increment i to just after the occurence of the current needle in haystack (use the find() string method or write your own function to handle this)
return true
0

? , , , re.search:

import re
bool(re.search('a.t.r', 'anteasters')) # True
bool(re.search('a.t.r', 'artist' ))    # False

, :

newstr = re.sub('\*', '.', 'a*t*r')    # Replace * with .
bool(re.search(newstr, 'anteasters'))  # Search using the new string

If regular expressions are not allowed, the easiest way to do this is to look at the substrings of the second line that are the same length as the first line, and compare them. Something like that:

def matchpat(str1, str2):
    if len(str1) > len(str2): return False  #Can't match if the first string is longer
    for i in range(0, len(str2)-len(str1)+1):
        substring = str2[i:i+len(str1)] # create substring of same length as first string
        for j in range(0, len(str1)):
            matched = False                        # assume False until match is found
            if str1[j] != '*' and str1[j] != substring[j]: # check each character
                break
            matched = True
        if matched == True: break # we don't need to keep searching if we've found a match
    return matched    
-1
source

Source: https://habr.com/ru/post/1528842/


All Articles