Problem:

Given a pattern string and a test string, Your task is to implement RegEx substring matching. If the pattern is preceded by a ^, the pattern(excluding the ^) will be matched with the starting position of the text string. Similarly, if it is preceded by a $, the pattern(excluding the ^) will be matched with the ending position of the text string. If no such markers are present, it will be checked whether pattern is a substring of test.

Example :

^coal
coaltar
Result : 1
tar$
coaltar
Result : 1
rat
algorate
Result: 1
abcd
efgh
Result :0
Input: The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains two lines. The first line of each test case contains a pattern string. The second line of each test case consists of a text string.

Output: Corresponding to every test case, print 1 or 0 in a new line.

Constrains:
1<=T<=100
1<=length of the string<=1000

Hint: Choosing the right language will probably help.

Implementation: Python 2.7

#code
def regx_matching(pattern, string):
    if pattern.startswith('^'):
        return string.startswith(pattern[1:]) 
    elif pattern.endswith('$'):
        return string.endswith(pattern[:-1])
    else:
        return pattern in string

if __name__ == '__main__':
    t = input()
    for _ in range(t):
        pattern = raw_input().strip()
        string = raw_input().strip()
        print 1 if regx_matching(pattern, string) else 0
Advertisements