Anchor Characters
Learn to validate the text using anchor characters.
Requirement of anchor characters
Let’s consider a scenario to learn about the need for anchor characters. Assume you have the task of writing a RegEx to match all of the phone records. You start with /\d{4}-\d{3}-\d{3}/
. This will work, so what is the problem? It will return a match in the following text “3234-524-53134” as well. But this is not the correct phone record. It should not be a match. So, how should you use RegEx to match the entire text? To match complete texts, RegEx has anchors characters.
Anchor characters appear at the beginning and the end of the text and are also used to validate data.
Caret character
The caret character creates a negative character set. But if you write the caret symbol at the very start of the RegEx, it will behave differently. The caret symbol ensures that the text starts with the specifically mentioned character only.
Let’s take a look at an example to learn it. Suppose you are provided with two texts, “123-345” and “abc123-456”. If you write RegEx /\d{3}-\d{3}/
, it will match both of them. Use caret symbol at the start and your RegEx will be /^\d{3}-\d{3}/
. If you again run the mentioned RegEx on both the texts, only one that starts with a number will match. You can mention grouping characters with it. For example, you can write the same RegEx for better readability as /^(\d{3}-\d{3})/
.
With a multi-line flag, the caret sign is used as well. For example, to match text that starts with the uppercase character “J”. RegEx /^J.*/
will match “Javascript”. All lines that begin with the uppercase letter “J” will match in multi-line mode.
Get hands-on with 1400+ tech skills courses.