Boundary Matchers

Now, we will learn how to match patterns at specific positions, like before, after or between some characters. For this purpose we use special characters like ^,$,\b & \B,\A,\z & \Z, which are known as anchors.

Notes:

It will show a match, only if the pattern is occuring at the start of the line.

It will show a match, only if the pattern is occuring at the end of a line.

Example, both ^ and $,

What did you observe? Our regex-pattern is starting and ending with a word character. So, the match occurs only if there is a substring starting and ending at word characters, which are required in our regex [a-z] and \d respectively.

Now, let's look at one more example.

<div class="container">
		

Here \+ will show a match for +, check it out in appendix.

What did you observe? First observation: Our pattern is starting with a non-word character and ending with a word character. So, the match occurs only if there is a substring having a non-word boundary at starting and word boundary at the ending.

Second observation: Non-word character after a word-boundary does not affect the result.

\b need not be used in pair. You can use a single \b.

\B is just a complement of \b. \B matches at all the positions that is not a word boundary. Observe two examples below:

Note: \A and \z & \Z are another anchors, which are used to match at the very start of input text and at very end of input text respectively. But it is not supported in Javascript.

Predict the output of the following regex:

  1. RegEx: ^[\w$#%@!&^*]{6,18}$
    Text: This is matching passwords of length between 6 to 18: Abfah45$ gadfaJ%33 Abjapda454&1 spc bjaphgu12$ Answer:
  1. RegEx: \b\w+:\B
    Text: 1232: , +1232:, abc:, abc:a, abc89, (+abc::) Answer: