Regular Expressions or regex or regexp or sometimes also referred to as rational expressions are :
There are two ways for creating an regular expression :
/
(slashes) as shown below :
var reg = /ab*/;
//It will match a , ab, abb , abbbbbb , abbbbbbb and so on.
//But will not match b, bc, abc,aba , etc.
RegExp
as shown below :
var reg = new RegExp('ab*');
//It will match a , ab, abb , abbbbbb , abbbbbbb and so on.
//But will not match b, bc, abc,aba , etc.
data.txt
synchronously and storing the content in
str
. After that we are providing with the pattern to look for in the file.In this case the pattern
is man
and further we are using regex modifiers :
match
. And lastly we are printing the Occurrences
of the pattern in the content string.
var fs = require('fs');
var filename = 'data.txt';
var str = fs.readFileSync(filename).toString();
var pattern = /man/gim;
var myarray = str.match( pattern );
var len = myarray.length;
console.log("Occurrences of pattern in the string is : " + len);
HTML
file as dataset for operation. tags
instead of string.
var fs = require('fs');
var filename = 'data.html';
var str = fs.readFileSync(filename).toString();
var pattern = /<(\"[^\"]*\"|'[^']*'|[^'\">])*>/gim;
var myarray = str.match( pattern );
var len = myarray.length;
console.log("Occurrences of pattern in the string is : " + len);
var str = 'rjbitdemo@gmail.com'
var pattern = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var res = str.match( pattern );
if(res){
console.log("Valid email address");
}else{
console.log("Please enter a valid email address");
}
var str = 'FFFFFF'
var pattern = /^[a-fA-F0-9]+$/g;
var res = str.match( pattern );
if(res){
console.log("Valid Hexadecimal number");
}else{
console.log("Not a valid Hexadecimal number");
}
var str = 'Aa#1aaabcde'
var pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;;
var res = str.match( pattern );
if(res){
console.log("Valid password");
}else{
console.log("Not a valid password");
}
In this part of nodejs tutorial series we learned about the following :