☼
⌃
☰

Regular expressions

Table of Contents

Regular Expressions

A regular expression (often shortened to regex or regexp) is a sequence of characters that specifies a search pattern. They are a powerful tool for inspecting and manipulating text.

Common Use Cases

  • Data Validation: Checking if input text, like emails, passwords, or phone numbers, conforms to a specific format.
  • Search and Replace: Finding specific patterns of text in a string or document and replacing them with something else.
  • Data Extraction/Scraping: Pulling specific information out of larger bodies of text, such as log files or web pages.
  • Syntax Highlighting: Identifying keywords, comments, and other language constructs in code editors.

Core Concepts

Literals and Metacharacters

  • Literals: Most characters (e.g., a, b, 1, 2) are literals and match themselves. The regex cat matches the string "cat".
  • Metacharacters: Special characters that have a unique meaning in the regex engine. The most common are: ., *, +, ?, ^, $, [, ], (, ), {, }, |, \. To match a metacharacter literally, you must escape it with a backslash (\), e.g., \. matches a literal period.

Character Classes (or Character Sets)

They specify a set of characters you wish to match.

  • [abc]: Matches a single character that is 'a', 'b', or 'c'.
  • [a-z]: Matches any single lowercase letter.
  • [^abc]: (Negation) Matches any single character except 'a', 'b', or 'c'.
  • \d: Matches any digit. Equivalent to [0-9].
  • \w: Matches any word character (alphanumeric + underscore). Equivalent to [a-zA-Z0-9_].
  • \s: Matches any whitespace character (space, tab, newline).
  • .: Matches any character except a newline.

Quantifiers

Quantifiers specify how many times the preceding character or group should be matched.

  • *: Zero or more times.
  • +: One or more times.
  • ?: Zero or one time (makes it optional).
  • {n}: Exactly n times.
  • {n,}: At least n times.
  • {n,m}: Between n and m times.

Anchors

Anchors don't match characters, but rather positions in the string.

  • ^: Start of the string.
  • $: End of the string.
  • \b: Word boundary (the position between a word character and a non-word character).

Grouping and Alternation

  • (): Groups multiple characters together. Quantifiers can then be applied to the whole group. e.g., (ab)+ matches "ab", "abab", "ababab", etc. Groups also "capture" the matched content for later use.
  • |: Acts as an OR operator. cat|dog matches either "cat" or "dog".

Modifiers

Modifiers (or flags) can be added to a regex to change its behavior. Common modifiers include:

  • i: Case-insensitive search.
  • g: Global search (find all matches, not just the first).
  • m: Multiline mode (^ and $ match the start/end of a line, not just the whole string).

Examples

  • Email Validation: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
  • Date (YYYY-MM-DD): ^\d{4}-\d{2}-\d{2}$
  • Find all words starting with 'c': \bc\w*