Day 3 Regular Expressions in node.js 30 Days of Node Summary

Day 3 Regular Expressions in node.js
30 Days of Node
Summary

Introduction

Regular Expressions or regex or regexp or sometimes also referred to as rational expressions are :

  • A sequence of characters expressing a pattern for further matching in a longer string.
  • It is a Text string to describe a pattern which can be used for searching.
  • They are a way to match pattern in the data and extracting the required information out of the data.
  • Regex provide a way to find patterns in the data. Finding patterns in data is one of the most commonly performed task in computing.
  • In everyday life we tend to find a lot of patterns. They could be email patterns , they could be phone numbers , keywords of a programming language, special characters , html tags and so on.
  • And all these can be achieved with the power of regular expressions.

Creating a regular expression

There are two ways for creating an regular expression :

  1. By regular expression literals : In this , the pattern to be matched is enclosed between the / (slashes) as shown below :

    let reg = /ab*/;
    // It will match a , ab, abb , abbbbbb , abbbbbbb and so on.
    // But will not match b, bc, abc, aba, etc.
    
  2. By calling the constructor function : In this, the pattern to be matched comes within the constructor function RegExp as shown below :

    let reg = new RegExp('ab*');
    // It will match a , ab, abb , abbbbbb , abbbbbbb and so on.
    // But will not match b, bc, abc, aba , etc.
    

Most common Examples

  1. Finding specific text using regular expression : The data set for this example is data.txt . In this, we are reading a file 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 :

    使用正则表达式查找特定文本:本示例的数据集为data.txt。在此,我们正在同步读取文件data.txt并将内容存储在str中。之后,我们提供了要在文件中查找的模式。在这种情况下,该模式是man,此外我们使用了regex修饰符:

    • g : global scope
    • i : case insensitive
    • m : multiline match

    and then we are performing the inbuilt function match. And lastly we are printing the Occurrences of the pattern in the content string.
    The code snippet is given below :

// regex-find-string.js 
const fs = require('fs');

const filename = 'data.txt';

const str = fs.readFileSync(filename).toString();

const pattern = /man/gim;

const myarray = str.match(pattern);

const len = myarray.length;

console.log(`Occurrences of pattern in the string is: ${len}`);
  1. Find number of tags using regular expression : The data set for this example is data.html . This example is somewhat similar to the above one except for the few changes which are :
  • We are providing an HTML file as dataset for operation.
  • Here the pattern is matching tags instead of string.

The code snippet is given below :

// regex-find-tags.js
const fs = require('fs');

const filename = 'data.html';

const str = fs.readFileSync(filename).toString();

const pattern = /<("[^"]*"|'[^']*'|[^'">])*>/gim;

const myarray = str.match(pattern);

const len = myarray.length;

console.log(`Occurrences of pattern in the string is: ${len}`);
  1. Validating emails using regular expression : In this we are giving a email as input in order to find out whether it met all the contraints of being a valid one.The pattern will match the constraints such as @ (1 Occurrence) , domain is provided , sub-domain , etc. After matching , if the email is a valid one it will console "Valid" and "Please enter a valid email" if the email provided is not a valid one.
    The code snippet is provided below :

    // regex-validate-email.js
    const str = 'rjbitdemo@gmail.com';
    const 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])?)*$/;
    
    const res = str.match(pattern);
    
    if (res) {
        console.log('Valid email address');
    } else {
        console.log('Please enter a valid email address');
    }
    

    Note : It will not check whether that email address is a valid one or whether that domain or sub domain exists or not. It will only check whether the email provided met all the constraints required for a valid email or not.

    注意:不会检查该电子邮件地址是否有效,或者该域及子域是否存在。它只会检查提供的电子邮件是否满足有效电子邮件所需的所有限制

  2. Validating Hexadecimal number using regular expression : This is also a very common example. In this we are checking/validating whether the provided string is a valid hexadecimal or not. Hexadecimal number ranges from :

    使用正则表达式验证十六进制数:这也是一个非常常见的示例。在此,我们正在检查/验证提供的字符串是否为有效的十六进制。十六进制数范围从:

    • [0-9]
    • [A-F]
    • [a-f]

    If the string provided is within this range then it's a valid one otherwise not and the code snippet provided below will check that :

    如果提供的字符串在此范围内,则它是有效的字符串,否则无效,下面提供的代码段将会检查:

    // regex-validate-hexadecimal.js
    const str = 'FFFFFF'
    const pattern = /^[a-fA-F0-9]+$/gim;
    
    const res = str.match( pattern );
    
    if (res) {
    	console.log("Valid Hexadecimal number");
    } else {
    	console.log("Not a valid Hexadecimal number");
    }
    
  3. Validating Password using regular expression : As we all must have observed that in order to make the password strong we provide the user with some criteria to be met for creating a password such as :

    使用正则表达式验证密码:众所周知,为了使密码更牢固,我们为用户提供了一些创建密码的条件,例如

    • Password must contain 1 capital letter [A-Z]
    • Password must contain 1 small letter [a-z]
    • Password must contain 1 number [0-9]
    • Password must contain 1 special character [!,@,#,$,%,^,. . . ] etc
    • Length of the password must be within the range [6 to 16]

    So we created a regex to validate whether the provided password met all the constraints or not. If the provided password met all the constraints it will console "Valid password" and the snippet will console "invalid password " if any of the above mentioned condition is not met.
    The snippet is provided below :

    因此,我们创建了一个正则表达式来验证所提供的密码是否满足所有约束条件。如果提供的密码满足所有约束条件,它将满足“有效密码”的要求,如果不满足上述任何条件,则代码段将提示“无效的密码”的信息

    // regex-validate-password.js
    const str = 'Aa#1aaabcde';
    const pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;;
    
    const res = str.match( pattern );
    if (res) {
    	console.log("Valid password");
    } else {
    	console.log("Not a valid password");
    }
    

    Summary

    In this part of nodejs tutorial series we learned about the following :

    • What are regular expressions
    • Creating regular expressions
      1. Using Regular expression Literals
      2. Using constructor Function
    • Common Examples of Regular Expressions
      1. Finding Specific text using Regular expression
      2. Finding Number of tags using Regular expression
      3. Validating Email using Regex.
      4. Validating Hexadecimal number using regexp
      5. Validating Password using regex