Search This Blog

2024/03/21

Javascript Regular Expression: pattern.compile method

A rather infrequently used method is compile(), which replaces an existing
regular expression with a new one.

This method takes the same arguments as the RegExp() constructor

A possible use of this function is for efficiency.Regular expressions declared
with the RegExp() constructor are “compiled” (turned into string matching
routines by the interpreter) each time they are used, and this can be a
time-consuming process, particularly if the pattern is complicated.

Explicitly calling compile() saves the recompilation overhead at each
use by compiling aregular expression once, ahead of time.

Lets consider following code.
Code:
var customer = "SANGRAM SHIAVJI DESAI 91-9890868345";

//this pattern has no subgroup so we will get sub expressions
var pattern = /[A-Z]{2,} [A-Z]{2,} [0-9]{2}-[0-9]{10}/;

var result1 = pattern.test(customer)

console.log("---------------------------Result 1: Pattern has no subgroups so no subexpression here---------------------------------------------")
console.log("Result 1:" + result1)
console.log("Matching SubString:")
console.log("First Name:" + RegExp.$1);
console.log("MIDDLE NAME:"+ RegExp.$2)
console.log("LAST NAME:"+ RegExp.$3)
console.log("PHONE NO:"+ RegExp.$4)
console.log("-------------------------------------------------------------------------------")


var customer = "SWAPNIL SUHAS SARDESHMUKH 91-9820345678";
pattern.compile("([A-Z]{2,}) ([A-Z]{2,}) ([A-Z]{2,}) ([0-9]{2}-[0-9]{10})");
var result2 = pattern.test(customer)

console.log("---------------------------Result 2:Pattern has subgroups so will get subexpression here ------------------------------------------")
console.log("Result 2:" + result2)
console.log("Matching SubString:")
console.log("First Name:" + RegExp.$1);
console.log("MIDDLE NAME:"+ RegExp.$2)
console.log("LAST NAME:"+ RegExp.$3)
console.log("PHONE NO:"+ RegExp.$4)
console.log("-------------------------------------------------------------------------------")

Output:
---------------------------Result 1: Pattern has no subgroups so no subexpression here---------------------------------------------
Result 1:true
Matching SubString:
First Name:
MIDDLE NAME:
LAST NAME:
PHONE NO:
-------------------------------------------------------------------------------
---------------------------Result 2:Pattern has subgroups so will get subexpression here ------------------------------------------
Result 2:true
Matching SubString:
First Name:SWAPNIL
MIDDLE NAME:SUHAS
LAST NAME:SARDESHMUKH
PHONE NO:91-9820345678
-------------------------------------------------------------------------------

No comments:

Post a Comment