Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Lecture 7 Re Part2 Split

Uploaded by

mudassirsabri45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 7 Re Part2 Split

Uploaded by

mudassirsabri45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

re.

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.

• Syntax : re.split(pattern, string, maxsplit=0, flags=0)

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)

[1, 3, 4, 'a', 'b', 'c']

from re import split

# '\W+' denotes Non-Alphanumeric Characters


# or group of characters Upon finding ','
# or whitespace ' ', the split(), splits the
# string from that point
print(split('\w+', 'Words, words , Words'))
print(split('\W', "Word's words Words"))

# Here ':', ' ' ,',' are not AlphaNumeric thus,


# the point where splitting occurs
print(split('\W+', 'On 12th Jan 2016, at 11:02 AM'))

# '\d+' denotes Numeric Characters or group of


# characters Splitting occurs at '12', '2016',
# '11', '02' only
print(split('\d+', 'On 12th Jan 2016, at 11:02 AM'))

['', ', ', ' , ', '']


['Word', 's', 'words', 'Words']
['On', '12th', 'Jan', '2016', 'at', '11', '02', 'AM']
['On ', 'th Jan ', ', at ', ':', ' AM']

from IPython.display import display, Image


display(Image(filename='flags.png'))
import re

# Splitting will occurs only once, at


# '12', returned list will have length 2
print(re.split('\d+', 'On 12th Jan 2016, at 11:02 AM', 1))

# 'Boy' and 'boy' will be treated same when


# flags = re.IGNORECASE
print(re.split('[a-f]+', 'Aey, Boy oh boy, come here',
flags=re.IGNORECASE))
print(re.split('[a-f]+', 'Aey, Boy oh boy, come here'))

['On ', 'th Jan 2016, at 11:02 AM']


['', 'y, ', 'oy oh ', 'oy, ', 'om', ' h', 'r', '']
['A', 'y, Boy oh ', 'oy, ', 'om', ' h', 'r', '']

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.

• Syntax: re.sub(pattern, repl, string, count=0, flags=0)


import re

# Regular Expression pattern 'ub' matches the


# string at "Subject" and "Uber". As the CASE
# has been ignored, using Flag, 'ub' should
# match twice with the string Upon matching,
# 'ub' is replaced by '~*' in "Subject", and
# in "Uber", 'Ub' is replaced.
print(re.sub('ub', '~*', 'Subject has Uber booked already',
flags=re.IGNORECASE))
# Consider the Case Sensitivity, 'Ub' in
# "Uber", will not be replaced.
print(re.sub('ub', '~*', 'Subject has Uber booked already'))

# As count has been given value 1, the maximum


# times replacement occurs is 1
print(re.sub('ub', '~*', 'Subject has Uber booked already',
count=1, flags=re.IGNORECASE))

# 'r' before the pattern denotes RE, \s is for


# start and end of a String.
print(re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam',
flags=re.IGNORECASE))

S~*ject has ~*er booked already


S~*ject has Uber booked already
S~*ject has Uber booked already
Baked Beans & Spam

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.subn(pattern, repl, string, count=0, flags=0)


import re

print(re.subn('ub', '~*', 'Subject has Uber booked already'))

t = re.subn('ub', '~*', 'Subject has Uber booked already',


flags=re.IGNORECASE)
print(t)
print(len(t))

# This will give same output as sub() would have


print(t[0])

('S~*ject has Uber booked already', 1)


('S~*ject has ~*er booked already', 2)
2
S~*ject has ~*er booked already
re.escape()
Returns string with all non-alphanumerics backslashed, this is useful if you want to match an
arbitrary literal string that may have regular expression metacharacters in it.

• Syntax: re.escape(string)
import re

# escape() returns a string with BackSlash '\',


# before every Non-Alphanumeric Character
# In 1st case only ' ', is not alphanumeric
# In 2nd case, ' ', caret '^', '-', '[]', '\'
# are not alphanumeric
print(re.escape("Awesome even"))
print(re.escape("I Asked what is this [a-9], he said \t ^WoW"))

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

regex = r"([a-zA-Z]+) (\d+)"

match = re.search(regex, "I was born on June 24")

if match != None:

print ("Match at index %s, %s" % (match.start(), match.end()))

print ("Full match: %s" % (match.group(0)))

# So this will print "June"


print ("Month: %s" % (match.group(1)))

# So this will print "24"


print ("Day: %s" % (match.group(2)))

else:
print ("The regex pattern does not match.")
Match at index 14, 21
Full match: June 24
Month: June
Day: 24

import re

s = "Welcome to Artificial intelligence "

# here x is the match object


res = re.search(r"\bA", s)

print(res.re)
print(res.string)

re.compile('\\bA')
Welcome to Artificial intelligence

Getting matched substring


group() method returns the part of the string for which the patterns match. See the below
example for a better understanding.

import re

s = "Welcome to Artificial Intelligence"

# here x is the match object


res = re.search(r"\D{3} t", s)

print(res.group())

ome t

# A Python program to demonstrate working of re.match().

import re
regex = r"([a-zA-Z]+) (\d+)"
match = re.search(regex, "I was born on June 24")
if match != None:

print ("Match at index %s, %s" % (match.start(), match.end()))

print ('date = ', match.group(0))

# So this will print "June"


print ("Month: %s" % (match.group(1)))
# So this will print "24"
print ("Day: %s" % (match.group(2)))

else:
print ("The regex pattern does not match.")

Match at index 14, 21


date = June 24
Month: June
Day: 24

Matching a Pattern with Text


re.match() : This function attempts to match pattern to whole string. The re.match function
returns a match object on success, None on failure.

re.match(pattern, string, flags=0)


• pattern : Regular expression to be matched.
• string : String where pattern is searched
• flags : We can specify different flags using bitwise OR (|).
# A Python program to demonstrate working
# of re.match().
import re

# a sample function that uses regular expressions


# to find month and day of a date.
def findMonthAndDate(string):

regex = r"([a-zA-Z]+) (\d+)"


match = re.match(regex, string)

if match == None:
print ("Not a valid date")
return

print ("Given Data: %s" % (match.group()))


print ("Month: %s" % (match.group(1)))
print ("Day: %s" % (match.group(2)))

# Driver Code
findMonthAndDate("Jun 24")
print("")
findMonthAndDate("I was born on June 24")
Given Data: Jun 24
Month: Jun
Day: 24

Not a valid date

Finding all occurrences of a pattern


re.findall() : Return all non-overlapping matches of pattern in string, as a list of strings. The
string is scanned left-to-right, and matches are returned in the order found

# A Python program to demonstrate working of


# findall()
import re

# A sample text string where regular expression


# is searched.
string = """Hello my Number is 123456789 and
my friend's number is 987654321"""

# A sample regular expression to find digits.


regex = '\d+'

match = re.findall(regex, string)


print(match)

# This example is contributed by Ayush Saluja.

['123456789', '987654321']

print([x for x in range(10) if x <2])

[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

You might also like