Regular Expression
Regular Expression
Regular Expressions
By
Assistant Professor
Department of E & TC
Password validation.
Ex: using RegEx we can apply rules for setting password. Like one capital, one
small letter, one number and one special character.
Expression Description
[^0-9] Find any character NOT between the brackets (any non-digit)
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 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.
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>
<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>
<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.
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