In the previous lesson, we learnt about the:

  • Beginning Special Character ^, for matching the beginning of a string, and the
  • Ending Special Character $, for matching the ending of a string

By combining these special characters in a pattern, we can validate a string from the beginning to the end. Let's see some examples:

Let's say you have a password requirement like: "8 characters minimum, only numbers, letters and underscore allowed".

Here's a regex pattern for that:

^\w{8,}$

In this pattern, you have \w{8,} which means 8 or more word characters. \w represents a word meta character which matches numbers, letters and the underscore.

By having the ^ at the beginning and $ at the end, the regex pattern now matches "the whole string from beginning to end". Let's apply this on some strings:

Regex/^\w{8,}$/
Input
Validate

Positive validation because "mypassword" is 10 characters (more than 8) and contains letters.

Regex/^\w{8,}$/
Input
Validate

Negative validation because although "anew$password" is 13 characters (more than 8), it contains a symbol that doesn't match the \w meta character.

Regex/^\w{8,}$/
Input
Validate

Positive validation because "hello123456789" is 14 characters (more than 8) and contains letters and numbers.

Regex/^\w{8,}$/
Input
Validate

Negative validation because "somethi" is 7 characters, less than 8.