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:
Validating a password
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:
Positive validation because "mypassword" is 10 characters (more than 8) and contains letters.
Negative validation because although "anew$password" is 13 characters (more than 8), it contains a symbol that doesn't match the \w meta character.
Positive validation because "hello123456789" is 14 characters (more than 8) and contains letters and numbers.
Negative validation because "somethi" is 7 characters, less than 8.