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:

  1. Anchor ^: It is used to match patterns at the very start of a line. For example,

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

  3. Anchor $: Similarly, $ is used to match patterns at the very end of a line.

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

    Example, both ^ and $,

  4. Anchors \b & \B: \b is called word boundary character.

    Below is a list of positions, which qualifies as a boundary for \b: If Regex-pattern is ending(or starting) with,

    So, in short \b is only looking for word-character at boundaries, so it is called "word boundary character".

    Let's first observe some examples to understand it's working:

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

    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:
  2. RegEx: \b\w+:\B
    Text: 1232: , +1232:, abc:, abc:a, abc89, (+abc::)
    Answer: