[go: up one dir, main page]

0% found this document useful (0 votes)
10 views71 pages

Unit 2 Part2

Uploaded by

THE AK GAM-MERS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views71 pages

Unit 2 Part2

Uploaded by

THE AK GAM-MERS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 71

1

Python Programming
ing Problem Solving Approach

Reema Thareja

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Decision Control
Statements

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Control Statements

A control statement is a statement that determines the control flow of a set of


instructions, i.e., it decides the sequence in which the instructions in a program are to
be executed.

Types of Control Statements —


• Sequential Control: A Python program is executed sequentially from the first line of
the program to its last line.
• Selection Control: To execute only a selected set of statements.
• Iterative Control: To execute a set of statements repeatedly.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


If Statement

Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
If-Else Statement

Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Nested if Statements
A statement that contains other statements is called a compound statement. To
perform more complex checks, if statements can be nested, that is, can be placed one
inside the other. In such a case, the inner if statement is the statement part of the
outer one. Nested if statements are used to check if more than one conditions are
satisfied.
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
If-elif-else Statement
Python supports if-elif-else statements to test additional conditions apart from the
initial test expression. The if-elif-else construct works in the same way as a usual if-
else statement. If-elif-else construct is also known as nested-if construct.

Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
While Loop

Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


For Loop
For loop provides a mechanism to repeat a task until a particular condition is True. It is
usually known as a determinate or definite loop because the programmer knows exactly
how many times the loop will repeat.
The for...in statement is a looping statement used in Python to iterate over a sequence of
objects.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


For Loop and Range() Function
The range() function is a built-in function in Python that is used to iterate over a
sequence of numbers. The syntax of range() is range(beg, end, [step])
The range() produces a sequence of numbers starting with beg (inclusive) and ending
with one less than the number end. The step argument is option (that is why it is placed
in brackets). By default, every number in the range is incremented by 1 but we can
specify a different increment using step. It can be both negative and positive, but not
zero.
Examples:

10

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Range() Function
If range() function is given a single argument, it produces an object with values from 0 to
argument-1. For example: range(10) is equal to writing range(0, 10).
• If range() is called with two arguments, it produces values from the first to the second.
For example, range(0,10).
• If range() has three arguments then the third argument specifies the interval of the
sequence produced. In this case, the third argument must be an integer. For example,
range(1,20,3).
Examples:

11

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Condition-controlled and Counter-controlled Loops

12

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Nested Loops
Python allows its users to have nested loops, that is, loops that can be placed inside
other loops. Although this feature will work with any loop like while loop as well as for
loop.
A for loop can be used to control the number of times a particular set of statements will
be executed. Another outer loop could be used to control the number of times that a
whole loop is repeated.
Example:
Loops should be properly indented to identify which statements are contained within
each for statement.

13

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
The Break Statement
The break statement is used to terminate the execution of the nearest enclosing loop in
which it appears. The break statement is widely used with for loop and while loop. When
compiler encounters a break statement, the control passes to the statement that follows
the loop in which the break statement appears.
Example:

14

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
The Continue Statement
Like the break statement, the continue statement can only appear in the body of a loop.
When the compiler encounters a continue statement then the rest of the statements in
the loop are skipped and the control is unconditionally transferred to the loop-
continuation
Example: portion of the nearest enclosing loop.

15

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
The Pass Statement
Pass statement is used when a statement is required syntactically but no command or
code has to be executed. It specified a null operation or simply No Operation (NOP)
statement. Nothing happens when the pass statement is executed.
Difference between comment and pass statements In Python programming, pass is a
null statement. The difference between a comment and pass statement is that while the
interpreter ignores a comment entirely, pass is not ignored. Comment is not executed
but pass statement is executed but nothing happens.
Example:

16

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


The Else Statement Used With Loops

Unlike C and C++, in Python you can have the else statement associated with a loop
statements. If the else statement is used with a for loop, the else statement is executed
when the loop has completed iterating. But when used with the while loop, the else
statement is executed when the condition becomes false.
Examples:

17

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Functions and Modules

18

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Functions
Python enables its programmers to break up a program into segments commonly known
as functions, each of which can be written more or less independently of the others.
Every function in the program is supposed to perform a well-defined task.

19

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Need for Functions
Each function to be written and tested separately.
• Understanding, coding and testing multiple separate functions is far easier.
Without the use of any function, then there will be countless lines in the code and
maintaining it will be a big mess.
• Programmers use functions without worrying about their code details. This speeds up
program development, by allowing the programmer to concentrate only on the code that
he has to write.
Different programmers working on that project can divide the workload by writing
different functions.
• Like Python libraries, programmers can also make their functions and use them from
different point in the main program or any other program that needs its functionalities. 20

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Function Declaration and Definition
• A function, f that uses another function g, is known as the calling function and g is
known as the called function.
• The inputs that the function takes are known as arguments/parameters.
• When a called function returns some result back to the calling function, it is said to
return that result.
• The calling function may or may not pass parameters to the called function. If the called
function accepts arguments, the calling function will pass parameters, else not.
• Function declaration is a declaration statement that identifies a function with its name,
a list of arguments that it accepts and the type of data it returns.
• Function definition consists of a function header that identifies the function, followed by
the body of the function containing the executable code for that function. 21

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Function Definition
Function blocks starts with the keyword def.
• The keyword is followed by the function name and parentheses (( )).
• After the parentheses a colon (:) is placed.
• Parameters or arguments that the function accept are placed within parentheses.
• The first statement of a function can be an optional statement - the docstring describe
what the function does.
• The code block within the function is properly indented to form the block code.
• A function may have a return[expression] statement. That is, the return statement is
optional. Example:

• You can assign the function name to a variable. Doing this will allow you to call same
function using the name of that variable. 22

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Function Call
The function call statement invokes the function. When a function is invoked the program
control jumps to the called function to execute the statements that are a part of that
function. Once the called function is executed, the program control passes back to the
calling function.
Function Parameters
A function can take parameters which are nothing but some values that are passed to it
so that the function can manipulate them to produce the desired result. These
parameters are normal variables with a small difference that the values of these variables
are defined (initialized) when we call the function and are then passed to the function.
Function name and the number and type of arguments in the function call must be same
as that given in the function definition.
23
Example:
If the data type of the argument passed does not matches with©that expected in function
OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
then an error is generated.
Examples

24

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Local and Global Variables

A variable which is defined within a function is local to that function. A local variable can
be accessed from the point of its definition until the end of the function in which it is
defined. It exists as long as the function is executing. Function parameters behave like
local variables in the function. Moreover, whenever we use the assignment operator (=)
inside a function, a new local variable is created.

Global variables are those variables which are defined in the main body of the program
file. They are visible throughout the program file. As a good programming habit, you
must try to avoid the use of global variables because they may get altered by mistake
and then result in erroneous output.
25

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Local and Global Variables
Example
:

26

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Using the Global Statement
To define a variable defined inside a function as global, you must use the global
statement. This declares the local or the inner variable of the function to have module
scope.
Exampl
e:

27

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Resolution of names
Scope defines the visibility of a name within a block. If a local variable is defined in a
block, its scope is that particular block. If it is defined in a function, then its scope is all
blocks within that function.
When a variable name is used in a code block, it is resolved using the nearest enclosing
scope. If no variable of that name is found, then a NameError is raised. In the code given
below, str is a global string because it has been defined before calling the function.
Exampl
e:

28

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
The Return Statement
The syntax of return statement is,
return [expression]
The expression is written in brackets because it is optional. If the expression is present,
it is evaluated and the resultant value is returned to the calling function. However, if no
expression is specified then the function will return None.
Example
:
The return statement is used for two things.
• Return a value to the caller
• To end and exit a function and go back to its caller

29

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Required Arguments

In the required arguments, the arguments are passed to a function in correct positional
order. Also, the number of arguments in the function call should exactly match with the
number of arguments specified in the function definition

Example
s:

30

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Keyword Arguments

When we call a function with some values, the values are assigned to the arguments
based on their position. Python also allow functions to be called using keyword
arguments in which the order (or position) of the arguments can be changed. The values
are not assigned to arguments according to their position but based on their name (or
keyword).
Keyword arguments are beneficial in two cases.
• First, if you skip arguments.
Exampl
• Second, if in the function call you change the order of parameters.
e:

31

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Variable-length Arguments
In some situations, it is not known in advance how many arguments will be passed to a
function. In such cases, Python allows programmers to make function calls with arbitrary
(or any) number of arguments.
When we use arbitrary arguments or variable length arguments, then the function
definition use an asterisk (*) before the parameter name. The syntax for a function using
variable arguments can be given as,

Exampl
e:

32

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Default Arguments
Python allows users to specify function arguments that can have default values. This means
that a function can be called with fewer arguments than it is defined to have. That is, if the
function accepts three parameters, but function call provides only two arguments, then the
third parameter will be assigned the default (already specified) value.
The default value to an argument is provided by using the assignment operator (=). Users can
specify a
Example:
default value for one or more arguments.

33

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Lambda Functions Or Anonymous Functions
Lambda or anonymous functions are so called because they are not declared as other
functions using the def keyword. Rather, they are created using the lambda keyword.
Lambda functions are throw-away functions, i.e. they are just needed where they have
been created and can be used anywhere a function is required. The lambda feature was
added to Python due to the demand from LISP programmers.
Lambda functions contain only a single line. Its syntax can be given as,
Example:

34

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Documentation Strings
Docstrings (documentation strings) serve the same purpose as that of comments, as they
are designed to explain code. However, they are more specific and have a proper syntax.

Example:

35

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Recursive Functions
A recursive function is defined as a function that calls itself to solve a smaller version of
its task until a final call is made which does not require a call to itself. Every recursive
solution has two major cases, which are as follows:
• base case, in which the problem is simple enough to be solved directly without making
any further calls to the same function.
• recursive case, in which first the problem at hand is divided into simpler sub parts.
Recursion utilized divide and conquer technique of problem solving.
Example:

36

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
The from…import Statement
A module may contain definition for many variables and functions. When you import a
module, you can use any variable or function defined in that module. But if you want to
use only selected variables or functions, then you can use the from...import statement.
For example, in the aforementioned program you are using only the path variable in the
sys module, so you could have better written from sys import path.
Example:

To import more than one item from a module, use a comma separated list. For example,
to import the value of pi and sqrt() from the math module you can write,
37

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Making your own Modules
Every Python program is a module, that is, every file that you save as .py extension is a
module.
Example
s:

38

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
The dir() function
dir() is a built-in function that lists the identifiers defined in a module. These identifiers
may include functions, classes and variables. If no name is specified, the dir() will return
the list of names defined in the current module.

Example:

39

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Modules and Namespaces
A namespace is a container that provides a named context for identifiers. Two identifiers
with the same name in the same scope will lead to a name clash. In simple terms, Python
does not allow programmers to have two different identifiers with the same name.
However, in some situations we need to have same name identifiers. To cater to such
situations, namespaces is the keyword. Namespaces enable programs to avoid potential
name clashes by associating each identifier with the namespace from which it originates.
Example
:

40

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Local, Global, and Built-in Namespaces
During a program’s execution, there are three main namespaces that are referenced- the
built-in namespace, the global namespace, and the local namespace. The built-in
namespace, as the name suggests contains names of all the built-in functions, constants,
etc that are already defined in Python. The global namespace contains identifiers of the
currently executing module and the local namespace has identifiers defined in the
currently executing function (if any).
When the Python interpreter sees an identifier, it first searches the local namespace,
then the global namespace, and finally the built-in namespace. Therefore, if two
identifiers with same name are defined in more than one of these namespaces, it
becomes masked.

41

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Local, Global, and Built-in Namespaces
Example:

42

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Module Private Variables
In Python, all identifiers defined in a module are public by default. This means that all
identifiers are accessible by any other module that imports it. But, if you want some
variables or functions in a module to be privately used within the module, but not to be
accessed from outside it, then you need to declare those identifiers as private.
In Python identifiers whose name starts with two underscores (__) are known as private
identifiers. These identifiers can be used only within the module. In no way, they can be
accessed from outside the module. Therefore, when the module is imported using the
import * form modulename, all the identifiers of a module’s namespace is imported
except the private ones (ones beginning with double underscores). Thus, private
identifiers become inaccessible from within the importing module.
43

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Packages in Python
A package is a hierarchical file directory structure that has modules and other packages
within it. Like modules, you can very easily create packages in Python.
Every package in Python is a directory which must have a special file called __init__.py.
This file may not even have a single line of code. It is simply added to indicate that this
directory is not an ordinary directory and contains a Python package. In your programs,
you can import a package in the same way as you import any module.
For example, to create a package called MyPackage, create a directory called MyPackage
having the module MyModule and the __init__.py file. Now, to use MyModule in a program,
you must first import it. This can be done in two ways.
import MyPackage.MyModule
or 44

from MyPackage import MyModule © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Globals(), Locals(), And Reload()

The globals() and locals() functions are used to return the names in the global and local
namespaces (In Python, each function, module, class, package, etc owns a “namespace”
in which variable names are identified and resolved). The result of these functions is of
course, dependent on the location from where they are called. For example,
If locals() is called from within a function, names that can be accessed locally from that
function will be returned.
If globals() is called from within a function, all the names that can be accessed globally
from that function is returned.
Reload()- When a module is imported into a program, the code in the module is executed
only once. If you want to re-execute the top-level code in a module, you must use the
reload() function. This function again imports a module that was previously imported. 45
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Python Strings

46

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Strings
Python treats strings as contiguous series of characters delimited by single, double or
even triple quotes. Python has a built-in string class named "str" that has many useful
features. We can simultaneously declare and define a string by creating a variable of
string type. This can be done in several ways which are as follows:
name = "India" graduate = 'N' country = name nationality = str("Indian")

Indexing: Individual characters in a string are accessed using the subscript ([ ])


operator. The expression in brackets is called an index. The index specifies a member of
an ordered set and in this case it specifies the character we want to access from the
given set of characters in the string.
The index of the first character is 0 and that of the last character is n-1 where n is 47the
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
number of characters in the string. If you try to exceed the bounds
RESERVED. (below 0 or above n-
Strings
Traversing a String: A string can be traversed by accessing character(s) from one
index to another. For example, the following program uses indexing to traverse a
string
Examplefrom first character to the last.
:

48

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Concatenating, Appending and Multiplying Strings
Examples:

49

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Strings are Immutable
Python strings are immutable which means that once created they cannot be changed.
Whenever you try to modify an existing string variable, a new string is created.
Example
:

50

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
String Formatting Operator
The % operator takes a format string on the left (that has %d, %s, etc) and the
corresponding values in a tuple (will be discussed in subsequent chapter) on the right.
The format operator, % allow users to construct strings, replacing parts of the strings
with the data stored in variables. The syntax for the string formatting operation is:
"<Format>" % (<Values>)
Example:

51

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Built-in String Methods and Functions

52

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Built-in String Methods and Functions

53

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Built-in String Methods and Functions

54

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Slice Operation
A substring of a string is called a slice. The slice operation is used to refer to sub-parts
of sequences and strings. You can take subset of string from original string by using [ ]
operator also known as slicing operator.

Examples:

55

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Specifying Stride while Slicing Strings
In the slice operation, you can specify a third argument as the stride, which refers to the
number of characters to move forward after the first character is retrieved from the
string. By default the value of stride is 1, so in all the above examples where he had not
specified the stride, it used the value of 1 which means that every character between two
index numbers is retrieved.
Examples:

56

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
ord() and chr() Functions
ord() function returns the ASCII code of the character and chr() function returns
Examples:by a ASCII number.
character represented

in and not in Operators


in and not in operators can be used with strings to determine whether a string is present
in another string. Therefore, the in and not in operator are also known as membership
operators.
Examples:

57

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Comparing Strings

58

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Iterating String
String is a sequence type (sequence of characters). You can iterate through the string
using for loop.
Examples:

59

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
The String Module
The string module consist of a number of useful constants, classes and functions (some
of which are deprecated). These functions are used to manipulate strings.
Examples:

60

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Working with Constants in String Module
You can use the constants defined in the string module along with the find function to
classify characters. For example, if find(lowercase, ch) returns a value except -1, then it
means that ch must be a lowercase character. An alternate way to do the same job is to
use the in operator or even the comparison operation.
Examples:

61

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Regular Expressions
Regular Expressions are a powerful tool for various kinds of string manipulation. These
are basically a special text string that is used for describing a search pattern to extract
information from text such as code, files, log, spreadsheets, or even documents.
Regular expressions are a domain specific language (DSL) that is present as a library in
most of the modern programming languages, besides Python. A regular expression is a
special sequence of characters that helps to match or find strings in another string. In
Python, regular expressions can be accessed using the re module which comes as a part
of the Standard Library
The Match Function
As the name suggest, the match() function matches a pattern to string with optional
flags. The syntax of match() function is, 62

re.match (pattern, string, flags=0) © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
EXAMPLE- Match() Function
Examples:

63

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
The search Function
The search() function in the re module searches for a pattern anywhere in the string. Its
syntax of can be given as, re.search(pattern, string, flags=0)
The syntax is similar to the match() function. The function searches for first occurrence
of pattern within a string with optional flags. If the search is successful, a match object
isExample:
returned and None otherwise.

64

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
The sub() Function
The sub() function in the re module can be used to search a pattern in the string and
replace it with another pattern. The syntax of sub() function can be given as,
re.sub(pattern, repl, string, max=0)
According to the syntax, the sub() function replaces all occurrences of the pattern in
Examplewith repl, substituting all occurrences unless any max value is provided. This
string
:
method returns modified string.

65

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
The findall() and finditer() Function
The findall() function is used to search a string and returns a list of matches of the
pattern in the string. If no match is found, then the returned list is empty. The syntax of
match() function can be given as,
matchList = re.findall(pattern, input_str, flags=0)
Example
s:

66

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Flag Options
The search(), findall() and match() functions of the module take options to modify the
behavior of the pattern match. Some of these flags are:
re.I or re.IGNORECASE — Ignores case of characters, so "Match", "MATCH", "mAtCh", etc
are all same
re.S or re.DOTALL — Enables dot (.) to match newline. By default, dot matches any
character other than the newline character.
re.M or re.MULTILINE — Makes the ^ and $ to match the start and end of each line. That
is, it matches even after and before line breaks in the string. By default, ^ and $
matches the start and end of the whole string.
re.L or re.LOCALE- Makes the flag \w to match all characters that are considered letters
in the given current locale settings. 67

re.U or re.UNICODE- Treats all letters from all scripts as word characters.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.
Metacharacters in Regular Expression

68

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Metacharacters in Regular Expression

69

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Character Classes
When we put the characters to be matched inside square brackets, we call it a
character class. For example, [aeiou] defines a character class that has a vowel
character.
Examples:

70

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS


RESERVED.
Groups
A group is created by surrounding a part of the regular expression with parentheses.
You can even give group as an argument to the metacharacters such as * and ?.

Example:

The content of groups in a match can be accessed by using the group() function.
For example,
• group(0) or group() returns the whole match. 71

• group(n), where n is greater than 0, returns the nth group from the left.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED.

You might also like