Regex with JavaScript Part 3

Match WhiteSpaces

During searching or matching a string. We come across a situation where we need to match spaces in String literals.

For matching spaces in String literals, we use \s  which is a lowercase s.

Example:



/**
* Checking for WhiteSpaces
*/

let checkForWhiteSpaces = "Remove WhiteSpaces from everywhere";
let spaceRegex=/\s/g;
console.log(checkForWhiteSpaces.match(spaceRegex));

OutPut:

Match Non-Whitespace Characters

Previously we had seen for searching white spaces using /s which lowercase s.

Here we are looking for searching Non-Whitespace and that can be done using /S , yes using upperCase s.

Example:



/**
 * Checking for WhiteSpaces
 */

 let checkForWhiteSpaces = "Remove WhiteSpaces from everywhere";
 let spaceRegex=/\s/g;
 console.log(checkForWhiteSpaces.match(spaceRegex));

OutPut:

Specify Upper and Lower Number of Matches

We can specify the lower and upper number of patterns with quantity specifiers.

Quantity specifiers are used within curly brackets ({ and }).

Example:



/**
 * specify upper and lower number of match
 */

let myString ="mmmmmmmk";
let mySecondString ="mk";
// match word "mmmmmmmk" only it has minimum 2 and maximum 4 'm'
let myRegex=/m{2,4}k/;
console.log(myRegex.test(myString));
console.log(myRegex.test(mySecondString));

OutPut:

Specify Only the Lower Number of Matches
Passed

Sometimes we need to match only a lower number of matches.

So To specify a lower number of matches keep the lower number of matches followed by comma in curly bracket ( { n, } ).

where n is a lower number.

Example:



/**
* specify lower number of match
*/

let myString ="pinnnnnnnnnnk";
let mySecondString ="pinnk";
// match word "pinnk" only it has four or more letter of n
let myRegex=/pin{4,}k/;
console.log(myRegex.test(myString));
console.log(myRegex.test((mySecondString)));

OutPut:

Specify Exact Number of Matches

Sometimes we need to specify an exact number of matches.

To specify an exact number of pattern just add that number in curly bracket.

Example:


/**
* specify exact match
*
*/

let myString = "apple";
let mySecondString ="aple";
//p should be appear two times
let myRegex = /ap{2}l/;
console.log(myRegex.test(myString));
console.log(myRegex.test(mySecondString));

OutPut:

Check for All or None

Sometimes we are not sure about the pattern that we are searching for. 

In that case, we use ‘?’ i.e question mark which check for zero or one of the preceding element.

In other words, we can also say that the previous character is optional i.e if that exists then fine and if not then also no problem.

Example:



/**
*
* Check for All or None
*/


let american ="favorite";
let british ="favourite";
let regexPattern = /favou?rite/;

//In this example 'u' is optional
console.log(regexPattern.test(american));
console.log(regexPattern.test(british));

OutPut:

Positive and Negative Lookahead

Lookaheads are patterns in Javascript that tells to Javascript to look-ahead in your string to check for pattern further long.

It can be helpful during searching multiple patterns on the same string.

There are two kinds of Lookaheads :

  • Positive lookahead
  • Negative lookahead

Positive lookahead :

– Look to make sure the element in the search pattern is there, but won’t actually match it.

– Positive Lookahead is used as (?= …)

– Where  the ... is the required part that is not matched.

Negative lookahead :

– Look to make sure the element in the search pattern is not there.

– Negative lookahead is used as (?!...) 

– where the ... is the pattern that you do not want to be there.

Example:



/**
 * lookahead 
 * 
 */

 let myPassword = "ohMyGod123";
 let mySecondPassword ="ohmyGod";
 // regex for a string greater than 5 character long and don't begin with number and have two consequitive numbers
 let myRegex = /^(?=\w{6}(?=\D+\d{2}))/;
 console.log(myRegex.test(myPassword));
 console.log(myRegex.test(mySecondPassword));

OutPut:

Check For Mixed Grouping of Characters Passed

Sometimes we need to match a group of Characters using regular expression.
We can achieve that using () i.e parenthesis.

Example :



/**
*  Mixed grouping Characters
*/

let myString = "laptop";
// check for multiple group of characters
let myRegex = /(lap|Desk)top/;
console.log(myRegex.test(myString));

OutPut:

Reuse Patterns Using Capture Groups

Some patterns are multiple times in a string. Then it is wastage of time to write the pattern multiple times for searching in a string.

Example:



/**
* Reuse patterns using capture Groups
*
*/

let myString ="mummy mummy mummy";
let myRegex = /(\w+)\s\1/;

console.log(myRegex.test(myString));

console.log(myString.match(myRegex));

OutPut:

Use Capture Groups to Search and Replace

We can search and after that replace in string using .replace().

.replace() contains two parameters :

  • First parameter the string that we are searching for
  • Second parameter the string from which we want to replace.

Example:



/**
* Capture group for search andd replace
*/

let myString= "Baba Black Sheep";
// replace Baba Black sheep with Sheep Black Baba
let myRegex = /(\w+)\s(\w+)\s(\w+)/
let myReplacementString= '$3 $2 $1';
console.log(myString.replace(myRegex,myReplacementString));

OutPut:

Remove Whitespace from Start and End

Sometimes we come across the problem that some string contains unwanted whitespaces and that we need to remove these whitespaces from our string.
For removing start and end whitespaces from a string from we use .trim()
method.

Example:



/***
* removing whitespace from string using .trim()
*/

let hello = "   Hello, World!  ";

let result = hello.trim();
console.log(result);

OutPut:

Regex with Javascript Part 2

In the previous post, we have started Regex with JavaScript and discussed some important points of Regex in JavaScript.

In today’s post, we are going to continue with the same topic.

Match Single Character with multiple possibilities

In the previous, we have discussed match pattern where we had dealt with a string pattern (/string/) and wildcard both (/./) and both have its own significance.

Where one finds the exact match and one works with everything.
We can also enhance this search using Character classes.
Character classes allows us to define a group of characters after placing them in square bracket ([ ]).

Example:



/**
 *  range number
 */


 let emailString = "krdheeraj51@gmail.com";
 let regexString = /[a-z@0-9]/g;
 console.log(emailString.match(regexString));

OutPut:

Match letters of Alphabet

In the case of Character match pattern, we can also define a range.
Suppose we have taken all characters from are then we can define our character classes like [a-e];

Example:



/**
* Character classes
*/

let catStr = "cat";
let batStr = "bat";
let ratStr = "rat";
let bgRegex = /[a-e]at/;

console.log(catStr.match(bgRegex));
console.log(batStr.match(bgRegex));
console.log(ratStr.match(bgRegex));

OutPut:

Match Numbers and letters of Alphabet

( – ) is not limited to matching range of character as we have seen previously. But it will also work to match a range of numbers.
For matching a number in between 10 to 15 we can write down like [ 10-15 ].

Example:



/**
*  range number
*/

let emailString = "krdheeraj51@gmail.com";
let regexString = /[a-z@0-9]/g;
console.log(emailString.match(regexString));

OutPut:

Match Single Characters not specified

Till now we have created a set of characters that we want to match.
We can also create a set of characters that we don’t want to match and these types of character sets are known as negated character set.

For using the negated character set we have to use caret character ( ^ ).

Example :

previous post

/**
* Ignore 0 to 9 and all vowel character
*
**/previous post

let quoteSample ="4th Umpire";
//create a regex for Ignore 0 to 9 and all vowel character
let myRegex = /[^0-9^aeiou]/gi;
console.log(quoteSample.match(myRegex));

OutPut:

Match Character that Occurs one or more time

Some times we need to match a group of Character that appears one or more than once.

We can check this case using + character. 

Remember::  In this case Character should be repeated consequently.

It means Character is being repeated one after another.

previous post suppose our String is “abc” and we are using our regex /a+/g then it will return [“a”].

But if our String is like “aabc” then it will return [“a”,”a”].

Example :



/**
* Handle case of matching zero or more Character
*/


let myString = "fuuuuuuuuuuun!!";
let realString = "It is funny time."
let moreString = "Not Interested.";

let myRegex = /fu*/i;

console.log(myString.match(myRegex));
console.log(realString.match(myRegex));
console.log(moreString.match(myRegex));

OutPut:

Match Characters that Occur Zero or More Times

The previous scenario handled the situation of occurring a Character one or more times.
At this time we will handle the same case of occurring a Character that may be occurred zero or more times.
Fo that that purpose we will use * Character.

Example:



/**
* Handle case of matching zero or more Character
*/

let myString = "fuuuuuuuuuuun!!";
let realString = "It is funny time."
let moreString = "Not Interested.";

let myRegex = /fu*/i;

console.log(myString.match(myRegex));
console.log(realString.match(myRegex));
console.log(moreString.match(myRegex));

OutPut:

 

More Post on Regex

Regex with Javascript

 

Regex with Javascript

Regex stands for Regular Expressions also known as Regexp are special strings that represent a search pattern.

For programmers, Regex is like pills that make our task easy.

Regex contains special meaning for some characters that we will explain in further discussion during this post.

Now we will perform some action using functions of Regular Expression.

Match String Using test() method :

As we know that Regex is used to match parts of string.
So, if we want to find “foodie” in the string “Tommy is a foodie.” then we have to use /foodie/ as expression.

Now /foodie/ is our Regex.

Note: Quote marks are not required within regular expression.

JavaScript has multiple ways to use Regex. One of the ways is to use test() method which returns true or false.

Syntax :



regex.test(string)
//return true or false

Example :



var myString = "Codeteaser";
//if our search pattern is teaser from above String
var myRegex = /teaser/;
console.log(myRegex.test(myString));

OutPut:

Match String Literals

We can follow the same approach with String Literals as we have followed previously for matching a string pattern form a strong. In this case, I am taking the same example which I had discussed at the beginning of the post.

Example :


var myStringLterals = "Tommy is a foodie.";
//Search for foodie from string literal
var myRegex =/foodie/;
console.log(myRegex.test(myStringLterals));

OutPut:

But from this approach another form of foodie like Foodie, FOODIE will not match.

Example :


var myStringLterals = "Tommy is a foodie.";
//Search for foodie from string literal
var myRegex =/Foodie/;
console.log(myRegex.test(myStringLterals));

OutPut:

Searching Multiple Option at a time

If we have a string literal “Ronny has a pet cat.” and we are not sure about pet name i.e it is cat or dog or whatever it is. But if we have to add as search pattern on this specific string literal then, in this case, we can follow this approach as shown below.

Example :


var myStringLiteral ="Ronny has a pet cat."
// search for pet name but not sure about pet name
var myRegex = /dog|cat/
console.log(myRegex.test(myStringLiteral));

OutPut:

Note :

We can search multiple patterns using OR or | operator.

Ignore Cases while matching

During matching pattern in a string literal, we had faced a problem while match pattern remains in different cases i.e upperCase (“A”, ”B”, “C” … “Z”) or lowerCases (“a”,”b”,”c” … “z”).
As we had discussed foodie, Foodie or FOODIE are different patterns and these dissimilarities are due to letter case differences.

So, we can ignore letter cases in pattern match using flags in Regex. There are various flags in Regex and ignoring case we will use i flag.

Example:


var myStringLterals = "Tommy is a foodie.";
//Search for foodie from string literal using i flag
var myRegex =/Foodie/i;
console.log(myRegex.test(myStringLterals));

OutPut:

Extract Matches

So till now, we have worked on pattern is existing or not in a String or String Literal. Now we going to extract match pattern from string.
For that purpose, we have to use .match() method.

Example:



/**
* Extrat match pattern
*/

var myExtractStringLiteral="Selena Gomez is a pop Singer.";
// Looking for match pattern
var myRegex =/Singer/;
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

Find more than first

match() method returns the first pattern from a string or string literal.

Example:



/**
* only find first pattern
*/

var myExtractStringLiteral = "Jonny Jonny yes papa";
// Looking for string pattern from a string literal
var myRegex =/Jonny/;
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

But if a string Literal contains multiple times the same pattern then in that case for returning all string pattern we use the g flag as shown in the upcoming example.

Example:



/**
* return all match pattern from a string literal 
*/

var myExtractStringLiteral = "Jonny Jonny yes papa";
// Looking for all match pattern inside String Literal
var myRegex =/Jonny/g;
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

Match anything with wildCard period

Sometimes we don’t know the exact pattern that we want to match. So, in that case, we have to try all possible words that we think for a matching pattern.
And i.e seriously a tough task.
But Regex contains wildCard character: . (dot)
The wildCard character will match anyone character of string.
The wildcard is also called a dot or period.
For example, if we have to match “hug”, “huh”, “hut” then our Regex pattern would be /hu./

Example:



/**
* wildCrad
*/


var myExtractStringLiteral = "I don't like fun during my working period.";
// Searching for fun
var myRegex =/fu./;
//After using dot it will match one character
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

Note: We will discuss more about Regex in further posts.