Regular Expressions -Quantifiers Part 2

This is the continuation of Regular Expressions – Quantifiers in which we will be discussing some of the new concepts in regular expressions i.e., grouping, handling of special characters, pipe operator, regex flags, and compile function.

Firstly, we will discuss the grouping i.e., parenthesis. Till now, in the regular expression pattern, we have used quantifiers preceded by a single character. If we wrap characters under the parentheses, the quantifier will look for repetition of the group of characters under the parenthesis. This concept is known as a grouping in the regular expression. For example, the pattern ‘(xyz){1, 2}’ will match the following strings:

  • xyz
  • xyzxyz

Similarly, the pattern (abc)+ will match:

  • abc
  • abcabc
  • abcabcabc, and so on.

Exercise 1: Grouping

Description

Write a regular expression that matches a string where ’45’ occurs one or more times followed by the occurrence of ’37’ one or more times

Sample positive matches (should match all of these):
4537
45453737
454545453737

Sample negative matches (shouldn’t match either of these):
45
37
45537
44537
44553377

Regular_Expression_Basics1

Now, let’s move to our next notation i.e., pipe operator represented by ‘|’ in the regular expression.

The pipe operator is to represent OR operation. We need to use the pipe operator inside the parentheses.

For example, the pattern ‘(w|t)ear’ will match both the strings – ‘wear’ and ‘tear’.

Similarly, the pattern ‘(SBI|Citi) Bank’ will match both the strings ‘SBI Bank’ and ‘Citi Bank’.

In addition, we can also use other quantifiers followed by parentheses with pipe operators inside them. Further, there can be multiple pipe operators inside the parentheses possible.

The pattern ‘(a|b|c){2} means ‘exactly two occurrences of either of a, b or c’s, and it will match to these strings – ‘aa’, ‘ab’, ‘ac’, ‘ba’, ‘bb’, ‘bc’, ‘ca’, ‘cb’ and ‘cc’.

Exercise 2: Pipe operator

Description

Write a regular expression that matches the following strings: 

  • Basketball 
  • Baseball 
  • Volleyball 
  • Softball 
  • Football
Regular_Expression_Basics1