Let’s discuss one more use of the grouping character with an alteration character.

Overview of alteration characters

Suppose you are provided with texts “argon, argan, argue”. One solution may be to use a wildcard character. To create an even more precise RegEx, you could use a character set. To match the texts, you will create one character set to match the fourth character and the other character set to match the fifth character. The final RegEx will be /arg[aou][ne]/.

However, this is not a precise text because the RegEx will create combinations. In the above example, RegEx will match “argae” or “argoe”, because the character set multiplies with each other. The RegEx engine will use any character from the first character set and any character from the second character set. In total, there are six different text combinations. RegEx has an alteration character to handle such situations.

Usage of alteration characters in RegEx

Let’s work on the solution for the above problem. One thing that is clear in your mind is the literal part “arg”. To use an alteration character with the remaining part, you can put the remaining group of characters next to the pipe symbol in the parentheses. For these texts RegEx will be /arg(on|an|ue)/. Now this RegEx will only match one of the mentioned words.

Alteration meta-characters act like the OR operator, which means it will match the expression to its left or right. It is denoted by the | (pipe symbol). The leftmost expression part gets preference over the rest of the groups. Rightmost is the least preferred, and you can use this property to make efficient RegEx.

Take another set of texts. You are asked to match the “Th” words like “These”, “This”, “The”, “Those”, “That” etc. As you are now familiar with the alteration character, you can separate the literal part and put the remaining into the groups with the alteration character. Your RegEx will have “Th” as a literal part, and the remaining parts of the texts are grouped with the alteration character. The final RegEx will look like /Th(e|ese|ose|at|is)/.

A small challenge to use alteration characters

Get hands-on with 1400+ tech skills courses.