Regex
Regex
Modifiers:
{1,3} we're expecting 1-3
+ Match 1 or more
? Match 0 or 1
* Match 0 or more
$ match the end of a string
^ match the beginning of a string
| matches either or e.g. \d{1-3}|\w{5-6}
[] Match range or "variance" e.g. [A-Za-z] or [1-5a-qA-Z]
{x} expecting "x" amount
DON'T FORGET!:
. + * ? [ ] $ ^ ( ) { } \ |
Regular Expression - Re
In many regex functions and methods, there are optional arguments called flags,
which modify the meaning of a given regex pattern.
import os
import re
# Enter your code here
def function(a):
match = re.match('^[AEIOU].*[aeiou]$',a)
return match
if __name__ == "__main__":
a = input()
b = function(a)
if b:
print(True)
else:
print(False)
Q2. insert two word string.if both strings start with 'e' then true else return
false
import os
import re
def function(a):
m = re.match('(e\w+)\s(e\w+)',a)
return m
if __name__ == "__main__":
a = input()
b = function(a)
if b:
print(True)
else:
print(False)
Q3. If string starts with capital letter, return true if it starts with anything
else return false
import os
import re
result = re.match('^[A-Z].*',a)
return result
if __name__ == "__main__":
a = input()
b = function(a)
if b:
print(True)
else:
print(False)
Q4: Extract names and values into dictionary from given string
import os
import re
# Enter your code here. Read input from STDIN. Print output to STDOUT
def main(x):
pattern = x
names = re.findall(r'[A-Z][a-z]*',pattern)
#print(names)
values = re.findall(r'\d{1,5}',pattern)
#print(values)
dicts = {}
x = 0
for eachName in names:
dicts[eachName] = values[x]
x += 1
return dicts
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
x=input()
print(main(x))
Input (stdin)
Download
{'Dhoni': '100', 'Kohli': '150', 'Rohit': '50', 'Dhawan': '250'}
Q5.
import os
import re
else :
hosts.append(re.findall(r'[a-z0-9]*\w\.[a-z0-9]*\w\.[a-z0-9]*\w',item)
[0])
print(hosts)
def func2():
timestamps = []
for item in sample_text:
timestamps.append(re.findall(r'\[(.*?)\]',item)[0])
print(timestamps)
def func3():
method_uri_protocol = []
for item in sample_text:
method_uri_protocol.append(tuple(re.findall(r'\"(.*?)\"',item)[0].split()))
print(method_uri_protocol)
def func4():
status = []
for item in sample_text:
status.append(re.findall(r'\s\d{3}\s',item)[0].strip())
print(status)
def func5():
content_size = []
for item in sample_text:
content_size.append(re.findall(r'.\s(\d{1,5})$',item)[0])
print(content_size)
'''For testing the code, no input is to be provided'''
if __name__ == "__main__":
func1()
func2()
func3()
func4()
func5()