Regular Expressions
Regular Expressions
Special Sequences
- Defines the basic predefined character class patterns.
- Represents a special meaning
- Consists of a special character prefixed with backslash
Ex: \A, \s
\A – Match pattern at start of string
\Z – Match pattern at end of string
\d – Match any digit
\D – Match any non digit
\s – Match any space
\S – Match any non space
\w – Match any alphanumeric character
\W – Match any alphanumeric character
line1 = "Arjun is a Infosys employee bearing employee id of 35489"
line2 = "His address is 11/23/345, Flat no 303, 65 Hills Singapore"
print(re.findall(r'\A([A-Z].*?)\s',line1))
print(re.findall(r'\A(A...n)\S',line1))
print(re.findall(r'\d+\Z',line1))
print(re.findall(r'\D+\Z',line2))
print(re.findall(r"\w{7}",line1))
print(re.findall(r"[0-9]",line2))
print(re.findall(r"[g-l1-4]",line2))
Exception Handling
- Exceptions are raised when program faces an error
- If error is not handled properly then the python interpreter will stop
process execution.
- To ensure the flow of program to run without interruptions, there is
need of handling these exceptions.
Syntax:
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pass
finally:
# execute always
Example:
class ValueSmallError(Exception):
pass
try:
n1 = int(input("Enter the number1 : "))
n2 = int(input("Enter the number2 : "))
if n1/n2 > 1:
print(f"{n1} is greater than {n2}")
else:
raise ValueSmallError
except ValueError:
print("Input should be of integer type")
except ZeroDivisionError:
print("Division cannot be possible with zero")
except ValueSmallError:
print("n1 value must be greater than n2")
finally:
print("Exception Handling is implemented")