Regular Expressions in Action

Regular Expressions in Action[edit | edit source]

To learn regular expression, we will learn how to write a pattern that will match all the possible spellings of Gaddafi, was a Libyan revolutionary, politician, and political theorist. So, there are 30 possible spellings of Gaddafi as shown below.

Gadaffi Gadafi Gadafy Gaddafi Gaddafy Gaddhafi Gadhafi Gathafi Ghadaffi Ghadafi Ghaddafi Ghaddafy Gheddafi Kadaffi Kadafi Kaddafi Kadhafi Kazzafi Khadaffy Khadafy Khaddafi Qadafi Qaddafi Qadhafi Qadhdhafi Qadthafi Qathafi Quathafi Qudhafi Kad'afi 

I use Regexpal, an online tool to test regular expressions.

Spelling 1: Matching Gadaffi[edit | edit source]

Let's start by matching the first spelling Gadaffi. To match this spelling, we can simply use /Gadaffi/g as our regular expression as shown below.

Regex-1.png

By default, matching is case-sensitive so Gadaffi and gadaffi are different. You can use flag \i to make search case-insensitive.

Spelling 2: Matching Gadafi[edit | edit source]

The first and second spelling differ with each other in number of f. Gadaffi has two fs and Gadafi has one. We can define these using quantifier like /Gadaf{1,2}i/g. The {1,2} tell the regular expression processor that there could be minimum 1 f and maximum 2 f in the search text. The braces are considered metacharacters.

Regex-2.png

Rather than defining a range like {1,2}, you can also define fixed values like f{5} which means there should be 5 f in the search text. Also, your upper limit can be open like {2,} which will mean 2 and above.

There are shorthand notation for common quantifier mentioned below:

* = {0,} zero or more

+ = {1,} one or more

? = {0,1} optional

Spelling 3: Matching Gadafy[edit | edit source]

The second and third spellings differ only in the last character -- i or y. In regular expression, you can define a set and any of the value in the set will be selected. The regular expression /Gadaf{1,2}[iy]/g means last character could be either i or y.

Regex3.png