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 ...

Access this course and 1400+ top-rated courses and projects.