Lecture 7 Re Part2 Split
Lecture 7 Re Part2 Split
split()
Split string by the occurrences of a character or a pattern, upon finding that pattern, the
remaining characters from the string are returned as part of the resulting list.
The First parameter, pattern denotes the regular expression, string is the given string in which
pattern will be searched for and in which splitting occurs, maxsplit if not provided is considered
to be zero ‘0’, and if any nonzero value is provided, then at most that many splits occur. If
maxsplit = 1, then the string will split once only, resulting in a list of length 2. The flags are very
useful and can help to shorten code, they are not necessary parameters, eg: flags =
re.IGNORECASE, in this split, the case, i.e. the lowercase or the uppercase will be ignored.
l = [1,3 ,4]
k = ['a','b','c']
print(l+k)
re.sub()
The ‘sub’ in the function stands for SubString, a certain regular expression pattern is searched in
the given string(3rd parameter), and upon finding the substring pattern is replaced by repl(2nd
parameter), count checks and maintains the number of times this occurs.
re.subn()
subn() is similar to sub() in all ways, except in its way of providing output. It returns a tuple with
count of the total of replacement and the new string rather than just the string.
• Syntax: re.escape(string)
import re
Awesome\ even
I\ Asked\ what\ is\ this\ \[a\-9\],\ he\ said\ \ \ \^WoW
re.search()
This method either returns None (if the pattern doesn’t match), or a re.MatchObject contains
information about the matching part of the string. This method stops after the first match, so
this is best suited for testing a regular expression more than extracting data.
import re
if match != None:
else:
print ("The regex pattern does not match.")
Match at index 14, 21
Full match: June 24
Month: June
Day: 24
import re
print(res.re)
print(res.string)
re.compile('\\bA')
Welcome to Artificial intelligence
import re
print(res.group())
ome t
import re
regex = r"([a-zA-Z]+) (\d+)"
match = re.search(regex, "I was born on June 24")
if match != None:
else:
print ("The regex pattern does not match.")
if match == None:
print ("Not a valid date")
return
# Driver Code
findMonthAndDate("Jun 24")
print("")
findMonthAndDate("I was born on June 24")
Given Data: Jun 24
Month: Jun
Day: 24
['123456789', '987654321']
[0, 1]
a = "Hello, World!"
print(a[2:4])
ll
len(a)
13
print(a[-5:-2])
orl
fruits = ["apple","banana","cherry"]
print(fruits[-2])
banana