Regular Expressions

  • Regular Expressions, commonly shortened to regex. is a special sequence of characters that describe a pattern of text that should be found or matched in a string or document.
  • By matching text, we can identify how often and where certain pieces of text occur, as well as have the opportunity to replace or update these pieces of text if needed.
  • Regular expressions operate by moving character by character, from left to right. When it finds a character that matches the first pieces of expression, it looks to find a continuous sequence of matching characters.
  • The simplest text that we can match with regular expressions is literals. This is where our regex contains the exact text that we want to match.
  • You can find two strings with the same regular expression using alternation, which is performed using the | symbol.
  • Character Sets, denoted by a pair of brackets [], let us match one character from a series of characters.'
  • We can make our character sets more powerful by using the ^ caret symbol placed at the front of the set will match any character which is not stated.
  • Wildcards . will match any single character in a piece of text. If you want to use an actual period inside a regex you can escape it with \.
  • Ranges [-] allow us to specify a range of characters that we want to match without having to type in every single character.
  • Shorthand Character Classes that represent common ranges make writing regular expressions much simpler.
    1. \w, the word character class represents the regex range [A-Za-z0-9_]
    2. \d, the digit character class represents the regex range [0-9].
    3. \s, the whitespace character class represents the regex range [\t \r\n\f\v]
    4. \W, the non-word character class represents the regex range [^A-Za-z0-9_].
    5. \D, the non-digit character class represents the regex range [^0-9]
    6. \S, the non-whitespace character class represents the regex range [^\t\r\n\f\v]
  • Grouping, denoted with a ( and ), lets us group of a regular expression together and allows us to limit alternation to that part of the regex.
  • Fixed Quantifiers, denoted with curly braces {}, let us indicate the exact quantity of a character we wish to match or allow us to provide a quantity range. Quantifiers are considered to be greedy as they will match the greatest quantity of characters they possibly can. \w{3}, \w{4,7}.
  • Optional Quantifiers, indicated by a question mark ?, allows us to indicate a character in a regex is optional, or can appear either 0 time or 1 time. humou?r.
  • Kleene Star *, is also a quantifier and matches the character 0 or more times. This means the character does not need to appear, can appear once, or more than once.
  • Kleene Plus +, is also a quantifier and matches the preceding character 1 or more times.
  • Anchors, ^, and $ are used to match text at the start and end of a string, respectively.

Comments