Javascript Regular Expressions grouping

Introduction

Parentheses in regular expressions are special characters that group together character patterns.

They are not themselves part of the characters to be matched.

If you want a number of expressions to be treated as a single group, you just enclose them in parentheses.

For example, /(\d\d)/.

Example

let myString = "JavaScript, VBScript and PHP"; 

How to match both JavaScript and VBScript using the same regular expression?

The only thing they have in common is that they are whole words and they both end in Script.

Well, an easy way would be to use parentheses to group the patterns Java and VB.

Then you can use the ? special character to apply to each of these groups of characters to make the pattern match any word having zero or one instance of the characters Java or VB, and ending in Script:

let myRegExp = /\b(VB)?(Java)?Script\b/gi; 

Breaking down this expression, you can see the pattern it requires is as follows:

  • A word boundary: \b
  • Zero or one instance of VB: (VB)?
  • Zero or one instance of Java: (Java)?
  • The characters Script: Script
  • A word boundary: \b

Putting these together, you get this:

let myString = "JavaScript, VBScript and PHP"; 
let myRegExp = /\b(VB)?(Java)?Script\b/gi; 
myString = myString.replace(myRegExp, "xxxx"); 
console.log(myString); /*from w  w w  . j ava2  s  . c  om*/

There is a potential problem with the regular expression you just defined.

As well as matching VBScript and JavaScript, it also matches VBJavaScript.

This is clearly not exactly what you meant.

To get around this you need to make use of both grouping and the special character |.

| is the alternation character.

It has an or-like meaning, similar to || in if statements, and will match the characters on either side of itself.

Your final code looks like this:

let myString = "JavaScript, VBScript and Perl"; 
let myRegExp = /\b(VB|Java)Script\b/gi; 
myString = myString.replace(myRegExp, "xxxx"); 
console.log(myString); //from ww  w.  j a  va2 s .  co m



PreviousNext

Related