String pattern recognition with regular expressions

Next up is "string patterns" - another strong point for regular expressions.
What are string patterns and why do I need RegExes for them?

A pattern is simply some repeating structure in strings There are many examples for finding patterns in a string:

  • Checking if a string has a certain number of characters
  • Checking if a string contains a desired number of dashes / underscores
  • Checking if a string contains a certain string - but only if it's a
  • Checking if string begins with a number
  • Checking if a string is a valid URL
  • Checking if a string is a valid email address

... I will go along the above examples to show you how RegEx does it ...


Checking if a string has a certain number of characters

A simple way to check the number of characters is by using the regex quantifiers.

Example usage

.{8} // matches exactly eight characters of any type (as designated by the dot)
// "12345678" will match
// "abcdefgh" will match
// "1234567"  will not match
// "123456789"will not match
// -> it matches ONLY exactly 8 characters
    

Further reading

Regex quantifiers


Was this page helpful?

Thank you for telling