Monday, July 6, 2020

Regular Expression

Write a regular expression that matches any string that starts with one or more ‘1’s, followed by three or more ‘0’s, followed by any number of ones (zero or more), followed by ‘0’s (from one to seven), and then ends with either two or three ‘1’s.

code snippet: 

Test case-1;

string = '11000011000111'

Test case-2: 

string = '00001100011111'

# regex pattern

#pattern = '^1{1, }0{3, }1{0, }0{1,7}1(2|3)$'

pattern =  '^1+0{3,}1*0{1,7}1{2,3}$'

# check whether pattern is present in string or not

result = re.search(pattern, string)

# evaluate result

if result != None:
    print(True)
else:
    print(False)


Explanation:



The ‘^’ specifies the start of the string. 

‘$’ specifies the end of the string.

|- Means OR (Matches with any of the characters separated by it.

* -Any number of occurrences (including 0 occurrences) 

+  - One or more occurrences 

{} - Indicate number of occurrences of a preceding RE to match.





No comments:

Post a Comment

Element wise operation on LIST vs ARRAY

The use of arrays over lists: You can write  vectorised  code on numpy arrays, not on lists, which is  convenient to read and write, and con...