0% found this document useful (0 votes)
2 views

Regular Expression

This document provides an overview of Regular Expressions (RegExp) in JavaScript, detailing their creation, usage, and various methods such as exec() and test(). It covers essential concepts including pattern matching, quantifiers, character classes, and advanced features like lookaheads and greedy matching. The document also includes practical examples and code snippets to demonstrate the application of regular expressions in string manipulation.

Uploaded by

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

Regular Expression

This document provides an overview of Regular Expressions (RegExp) in JavaScript, detailing their creation, usage, and various methods such as exec() and test(). It covers essential concepts including pattern matching, quantifiers, character classes, and advanced features like lookaheads and greedy matching. The document also includes practical examples and code snippets to demonstrate the application of regular expressions in string manipulation.

Uploaded by

khushi.shelote
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit 4

Regular Expressions

By

Mrs. Sanjyot Thuse

Assistant Professor

Department of E & TC

PES Modern College of Engineering


Contents

 The Need for Regular Expressions, Introduction to JavaScript Regular


Expressions, Creating Patterns.
 Repetition Quantifiers, Grouping, Common Character Classes, RegExp
Object, exec().
 String Methods for Regular Expressions: search(), split(),replace(),replace()
with Sub expressions.
 Advanced Regular Expressions: Multiline Matching, Non-capturing
Parentheses, Lookahead.
 Greedy Matching, Limitations of Regular Expressions.
The Need for Regular Expressions (RegExp)

 A regular expression is an object that describes a pattern of characters.

 It is used for pattern matching or string matching.

 Its real-time application is to validate email Id.

 Password validation.

Ex: using RegEx we can apply rules for setting password. Like one capital, one
small letter, one number and one special character.

 regular expressions are used to perform powerful pattern-matching and


search-and-replace functions on text.
Creating a Regular Expression
 There are two ways to create a regular expression in JavaScript.
1. It can either be created with a RegExp constructor
Syntax:
var pattern = new RegExp(“pattern”, “attributes”);
Ex: var regexConst = new RegExp('abc’);
2. using forward slashes ( / ) to enclose the pattern.
Synatx:
var pattern = /pattern/attributes;
Ex: var regexLiteral = /abc/;
Hello!! abc, how do you find your room / grab the crab in your plate
pattern − A string that specifies the pattern of the regular expression or another regular
expression.
Attributes (flag) − An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multi-line matches, respectively.
 Find a match using simple patterns:
Simple patterns are constructed of characters for which you want to find a direct match. The
pattern /abc/ matches character combinations in strings only when the exact
sequence "abc" occurs (all characters together and in that order)
Ex1: Hello!! abc, how do you find your room
var data = /abc/;
o/p is abc
Ex 2: Grab the crab on your plate
var data = /abc/;
There is no match in the string "Grab crab" because while it contains the substring "ab“ ,’c’ ,”ab”,
it does not contain the exact substring "abc".
 Using special characters
When the search for a match requires something more than a direct match, such as finding one or
more b's, or finding white space, you can include special characters in the pattern.
Pattern /ab*c/: the * after "b" means "0 or more occurrences of the preceding item.
For string abababbbcaabbcc
var data = /ab*c/;
The pattern abbbc will be matched the the above given string
Regular Expression: Brackets

Expression Description

[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets

[0-9] Find any character between the brackets (any digit)

[^0-9] Find any character NOT between the brackets (any non-digit)

(a|b) Find any of the alternatives specified


Regular Expression: Flags

Flag Description
g Perform a global match (find all matches rather than stopping after
the first match)

i Ignore case
m Perform multiline matching
^ and & are used in multiline match.
^ specifies start of the string
& specifies end of the string
Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted by a
special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a
character sequence.
Sr.No. Expression & Description Example
p+ In string “hello I am on a run” ; var data = /o+/
1
It matches any string containing one or more p's. o/p : oo
p* in string “hello world”; var data = /l0+/
2
It matches any string containing zero or more p's. o/p: l,lo,o,lo
p? In string “ 100010” ; var data=/10?/
3
It matches any string containing zero or one occurrence of p. o/p: 10
p{N} In string “ 1000, 100, 10000 ” ; var data=/0{4}/
4
It matches any string containing a sequence of N p's o/p: 0000
let text = "100, 1000 or 10000?";
p{2,3}
5 let pattern = /\d{3,4}/g;
It matches any string containing a sequence of two or three p's.
o/p: 100, 1000
let text = “1, 10,100, 1000 or 10000?";
p{2, }
6 let pattern = /\d{2}/g;
It matches any string containing a sequence of at least two p's.
o/p: 10
let text = "Is this his";
p$
7 let pattern = /is$/;
It matches any string with p at the end of it.
o/p: is
let text = "Is this his";
^p
8 let pattern = /^Is/g;
It matches any string with p at the beginning of it.
Regular Expression: Metacharacters
Metacharacter Description
.. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word, beginning like this: \bHI, end like this:
HI\b
\B Find a match, but not at the beginning/end of a word
\0 Find a NULL character
\n Find a new line character
\f Find a form feed character (page separator)
\r Find a carriage return character (return to the beginning of the current line)
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
\xdd Find the character specified by a hexadecimal number dd
\uddd Find the Unicode character specified by a hexadecimal number dddd
The exec() method

 The exec() method takes a string as the parameter. This string is which is to be checked for
match in the given string.
 The exec() method makes a search for the specified match of the string in the given string.
 If the match of the string is present in the given string it returns an array and if the match is not
found in the given string, then it returns a null value.
Syntax:
regularExpressionObj.exec(string)
Ex: var search1 = new RegExp("JavaScript");
Program to demonstrate exec()
O/P:

<html>
<head>
<title> exec() - Regular Expression in JavaScript</title>
</head>
<body>
<p>click to get exec() method output</p>
<button onclick="findMatch()">Search</button>
<p id="tutorial"></p>
<script>
function findMatch() {
var txt ="Reena is Learning regular expressions in JavaScript";
var search1 = new RegExp("JavaScript");
var search2 = new RegExp("Akshay")
var res1 = search1.exec(txt);
var res2 = search2.exec(txt);
document.getElementById("tutorial").innerHTML ="Given string is:"+txt +"<br>"+"Result of two
search keys: "+res1+"<br>"+res2
}
</script>
</body>
</html>
Program 2: to demonstrate exec()
<html>
<body>

<h2>JavaScript RegExp</h2>

<p>The exec() method tests for a match in a string:</p>


<p>Search a string for the character "gone":</p>

<p id="demo"></p>
<script>
let text = "Time is money. Money gone can be earned. Time gone then gone";
let result = /gone/.exec(text);
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>

*** case-sensitive
The test() method
 The test() method makes a search for the specified match of the string in the given string.

 The difference between the exec() and test() methods is that the exec() method will return the
specified match if present or null if not present in the given string whereas the test() method
returns a Boolean result i.e., true if the specified match is present or else returns false if it is not
present.

 Syntax:

regularExpressionObj.test(string)

This also takes the given input string as the parameter and returns the Boolean result.

Ex: var res1 = search1.test(txt);


Program to demonstrate test()
<html>
<head>
<title>test() - Regular Expression in JavaScript</title>
</head>
<body>
<p>click to get test() method output</p>
<button onclick="findMatch()">Search</button>
<p id="tutorial"></p>
<script>
function findMatch() {
var txt ="Reena is trying to Learn regular expressions in JavaScript";
var search1 = new RegExp("Java");
var search2 = new RegExp("Reena")
var res1 = search1.test(txt);
var res2 = search2.test(txt);
document.getElementById("tutorial").innerHTML ="Given string is:"+txt+"<br>"+"Result of two
search keys: "+res1+" "+res2
}
</script>
</body>
</html>
String Methods for Regular Expressions: search()

 The search() method searches a string for a specified value and returns the position of the match.
 If match is not found then it returns -1
<html>
<body>
<h2>JavaScript Regular Expressions search()</h2>
<p id="demo"></p>
<script> o/p:
let text = "Cat Schools!"; 4
Position of
let n = text.search(/school/i); first
document.getElementById("demo").innerHTML = n; character in
the string
</script>
</body>
</html>
String Methods for Regular Expressions: split()
Using String replace() With a String
<html>
<body>
<h1>JavaScript String Methods</h1>
<h2> String replace</h2>
<p>Replace “MCOE" with "ModernCollege" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction()
{
let text = "Please Visit PES MCOE";
document.getElementById("demo").innerHTML = text.replace("MCOE","ModernCollege");
}
</script>

</body>
Use String replace() With a Regular Expression
<html>
<body>

<h2>JavaScript String Methods</h2>


<h2> String replace with regular expression</h2>
<p>Replace "MCOE" with "Modern" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction()
{
let text = "Please Visit PES MCOE";
document.getElementById("demo").innerHTML =text+"br";
document.getElementById("demo").innerHTML =
text.replace(/MCOE/i, "Modern");
}
</script>
</body>
</html>
Advanced Regular Expressions: Multiline Matching
To perform multiline matching, use the M modifier available in JavaScript Regular Expression.

const regex2 = /line/gim;


const multiLineStr =
`Line 1 o/p:
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7`;

console.log(regex2.test(multiLineStr)); // true

if (regex2.test(multiLineStr)) {
console.log('There are multiple matches'); //
There are multiple matches
} else {
console.log('Found no match');
}
Advanced Regular Expressions: Capturing groups and Non-capturing Parentheses
Capturing groups
 Capturing group is a group of characters or a character written in parenthesis ( ).
 The content in the bracket will be retrieved separately.
Ex: I am a student of MCOE
/I \sam\sa\s(\w+)\sof\sMCOE
 Extracting username in email ID using capturing group.
[email protected]

Non-Capturing groups
 Non-Capturing group is a group of characters or a character written in parenthesis ( ) with ?: at
the start to exclude the regular expression.
const regex = /^(?:Mr\.|Ms\.) ([A-Za-z]+)$/;
const str1 = 'Mr. Ramnathan';
const str2 = 'Ms. Krishna';
console.log(regex.exec(str1));
console.log(regex.exec(str2));
Lookaheads in JS
 Lookaheads are the patterns to look ahead in the string to check for desiered patterns in the string. Lookahead and
Lookbehind are referred to together as Lookaround.
 Syntax:
X(?=Y) //For positive lookaheads
X(?!Y) //For negative lookaheads
Types of lookaheads: There are two types of lookaheads as follows:
Positive lookaheads: It will look to make sure that a particular element is there in the search pattern, but actually won’t
match it. A positive lookahead is created by enclosing a certain pattern between (?= and ).
Example: let word1 = "butterfly";
let exp = /(butter(?=fly))/
let result1 = (exp.test(word1))
console.log(result1); //outputs “true”
exp matches “butter” only if it is followed by “fly“
Negative lookaheads: It will look to make sure that a particular element is not there in the search pattern. A negative
lookahead is create
let word1 = "butterfly";
let exp = /(butter(?!fly))/
let result1 = (exp.test(word1))
console.log(result1); //outputs “false”
exp does not matches “butter” as it should not be followed by “fly“
Greedy Match
 This is the maximum possible match in the given string. This is termed as
greedy match
We can use exec(), test() or match function to demonstrate this.
Thank You

You might also like