Regular expression are often used to make sure that a string matches a certain pattern. For example, that a string looks like a zip code, or phone number, or e-mail address.
The simplest regular expression is just a sub-string. For example, the regular expression ther matches the string hello there, because the string contains the regular expression.
Start and End of Line
You can easily match strings that start or end with certain characters. The ^ character matched the start of the string. For example:
^hello Matches hello there, hello Shaikh, hellotopical
To match the end
of the string, use the $ character. For example:
Matches Where, and There
and $ characters are know as “Atomic Zero Width Assertions”,
in case you were wondering.
Character classes allow you to specify sets of characters or ranges. For example:
Matches Hey, and Hi, but not Zzz
In other words,
the string must contain at least one of the characters in the character class.
You can also exclude characters. For example:
Matches Zzz, but not Hey or Hi.
When the ^
character is the first character in the character class, it means “anything but the following characters”.
Putting this together, we could create a pattern that matches strings that start with a vowel:
[aeiou] Or, strings that don’t start with a vowel: [^aeiou]
With character classes, you can also specify ranges. For example:
Matches 0, 5, 8, or any number between 0 and 9.
Matches any two digit number (04, 13, 87, etc.), but there’s a better way to do this.