Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Regex Syntax and Basic Patterns | Introduction to Regular Expressions
Python Regular Expressions

Regex Syntax and Basic Patterns

Swipe to show menu

Regex Syntax: Building Blocks

Regular expressions, or regex, are constructed using a combination of literals, metacharacters, character classes, and quantifiers. Understanding these components is essential for writing effective patterns.

  • Literals are ordinary characters that match themselves. For example, the pattern "cat" matches the exact string "cat";
  • Metacharacters are special symbols that have unique meanings in regex. The most common metacharacters include:
    • . (dot): matches any single character except a newline;
    • ^: matches the start of a string;
    • $: matches the end of a string;
    • *: matches zero or more occurrences of the preceding element;
    • +: matches one or more occurrences of the preceding element;
    • ?: matches zero or one occurrence of the preceding element.
  • Character classes allow you to match any one character from a set of characters. For example, [abc] matches "a", "b", or "c", and [0-9] matches any digit from 0 to 9.

Useful Letter-Based Metacharacters and Quantifiers

  • \w: matches any word character (equivalent to [a-zA-Z0-9_]). Use this to match single letters, digits, or underscores;
  • \W: matches any non-word character (anything not matched by \w);
  • \d: matches any digit (equivalent to [0-9]);
  • \D: matches any non-digit character;
  • \b: matches a word boundary (the position between a word character and a non-word character). Use this to match words as whole units;
  • \B: matches a position not at a word boundary.

Quantifiers

Quantifiers specify how many times the preceding element must occur:

  • *: matches zero or more times; for example, \w* matches any sequence of word characters, including an empty string;
  • +: matches one or more times; for example, \w+ matches one or more consecutive word characters (such as a word);
  • ?: matches zero or one time; for example, \w? matches zero or one word character;
  • {n}: matches exactly n times; for example, \w{3} matches exactly three word characters in a row;
  • {n,}: matches n or more times; for example, \w{2,} matches two or more word characters;
  • {n,m}: matches between n and m times; for example, \w{2,5} matches from two to five word characters in a row.

Examples in Python

  • re.findall(r"\w+", "Regex123 is fun!") returns all words: ["Regex123", "is", "fun"];
  • re.findall(r"\bcat\b", "The cat scattered the catalog.") matches only the standalone word "cat";
  • re.findall(r"\w{5}", "apple banana kiwi") finds all sequences of exactly five word characters: ["apple", "banan"].

These metacharacters and quantifiers are essential for matching letters, words, and word-like patterns in text using Python's re library.

123456789101112131415
import re text = "User123, admin42, guestX" # Find all digits digits = re.findall(r"[0-9]", text) print("Digits found:", digits) # Find all lowercase letters lowercase_letters = re.findall(r"[a-z]", text) print("Lowercase letters found:", lowercase_letters) # Find all uppercase letters uppercase_letters = re.findall(r"[A-Z]", text) print("Uppercase letters found:", uppercase_letters)

In this example, you use the re.findall() function to search for matches in the string "User123, admin42, guestX". The pattern [0-9] matches any digit between 0 and 9, so it finds all individual digits in the text. The pattern [a-z] matches any lowercase letter from "a" to "z", and [A-Z] matches any uppercase letter from "A" to "Z". Each character class is enclosed in square brackets, specifying the range or set of characters to match. These patterns are fundamental in extracting specific types of characters from text.

123456789101112131415161718192021222324252627
import re text = "Hello_123 world! Regex is fun." # \w matches any word character (alphanumeric or underscore) word_chars = re.findall(r"\w", text) print("Word characters (\\w):", word_chars) # \W matches any non-word character non_word_chars = re.findall(r"\W", text) print("Non-word characters (\\W):", non_word_chars) # \b matches word boundaries words = re.findall(r"\b\w+\b", text) print("Words using word boundaries (\\b):", words) # * quantifier: zero or more word characters after 'o' pattern_star = re.findall(r"o\w*", text) print("'o' followed by zero or more word characters (o\\w*):", pattern_star) # + quantifier: one or more word characters after 'R' pattern_plus = re.findall(r"R\w+", text) print("'R' followed by one or more word characters (R\\w+):", pattern_plus) # ? quantifier: 'l' optionally followed by 'e' pattern_question = re.findall(r"le?", text) print("'l' optionally followed by 'e' (le?):", pattern_question)

Here you can see how to use Python's re.findall() function with various regex patterns to extract information from the string "Hello_123 world! Regex is fun.". Here is what each pattern does:

  • \w: The pattern r"\w" matches any word character, which includes letters (both uppercase and lowercase), digits, and the underscore (_). In the given string, this finds every individual word character, such as 'H', 'e', 'l', 'o', '1', '2', '3', and so on.

  • \W: The pattern r"\W" matches any non-word character. This includes spaces, punctuation, and symbols that are not letters, digits, or underscores. In the string, this finds characters like spaces, the exclamation mark (!), and the period (.).

  • \b: The pattern r"\b\w+\b" uses word boundaries (\b) to match complete words. Here, \w+ matches one or more word characters, so this extracts entire words such as 'Hello_123', 'world', 'Regex', 'is', and 'fun' as separate elements.

  • * quantifier: The pattern r"o\w*" matches the character 'o' followed by zero or more word characters. This means it will match 'o' even if it is not followed by any word characters, or it will capture a sequence starting with 'o' and continuing through any following word characters. In the string, this finds 'o_123' (from 'Hello_123') and 'orld' (from 'world').

  • + quantifier: The pattern r"R\w+" matches the character 'R' followed by one or more word characters. This is useful for finding words that start with 'R' and continue with additional word characters. In the string, this finds 'Regex'.

  • ? quantifier: The pattern r"le?" matches the letter 'l' optionally followed by 'e'. The ? quantifier means the preceding character ('e') can appear zero or one time. This pattern will match both 'l' and 'le' wherever they occur in the string.

Each of these patterns highlights a key feature of regular expressions—matching specific character types, boundaries, and repeated elements—making it easier to extract or analyze information from text in Python.

question mark

What does the regex pattern [a-z] match?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 2

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Regex Syntax and Basic Patterns

Regex Syntax: Building Blocks

Regular expressions, or regex, are constructed using a combination of literals, metacharacters, character classes, and quantifiers. Understanding these components is essential for writing effective patterns.

  • Literals are ordinary characters that match themselves. For example, the pattern "cat" matches the exact string "cat";
  • Metacharacters are special symbols that have unique meanings in regex. The most common metacharacters include:
    • . (dot): matches any single character except a newline;
    • ^: matches the start of a string;
    • $: matches the end of a string;
    • *: matches zero or more occurrences of the preceding element;
    • +: matches one or more occurrences of the preceding element;
    • ?: matches zero or one occurrence of the preceding element.
  • Character classes allow you to match any one character from a set of characters. For example, [abc] matches "a", "b", or "c", and [0-9] matches any digit from 0 to 9.

Useful Letter-Based Metacharacters and Quantifiers

  • \w: matches any word character (equivalent to [a-zA-Z0-9_]). Use this to match single letters, digits, or underscores;
  • \W: matches any non-word character (anything not matched by \w);
  • \d: matches any digit (equivalent to [0-9]);
  • \D: matches any non-digit character;
  • \b: matches a word boundary (the position between a word character and a non-word character). Use this to match words as whole units;
  • \B: matches a position not at a word boundary.

Quantifiers

Quantifiers specify how many times the preceding element must occur:

  • *: matches zero or more times; for example, \w* matches any sequence of word characters, including an empty string;
  • +: matches one or more times; for example, \w+ matches one or more consecutive word characters (such as a word);
  • ?: matches zero or one time; for example, \w? matches zero or one word character;
  • {n}: matches exactly n times; for example, \w{3} matches exactly three word characters in a row;
  • {n,}: matches n or more times; for example, \w{2,} matches two or more word characters;
  • {n,m}: matches between n and m times; for example, \w{2,5} matches from two to five word characters in a row.

Examples in Python

  • re.findall(r"\w+", "Regex123 is fun!") returns all words: ["Regex123", "is", "fun"];
  • re.findall(r"\bcat\b", "The cat scattered the catalog.") matches only the standalone word "cat";
  • re.findall(r"\w{5}", "apple banana kiwi") finds all sequences of exactly five word characters: ["apple", "banan"].

These metacharacters and quantifiers are essential for matching letters, words, and word-like patterns in text using Python's re library.

123456789101112131415
import re text = "User123, admin42, guestX" # Find all digits digits = re.findall(r"[0-9]", text) print("Digits found:", digits) # Find all lowercase letters lowercase_letters = re.findall(r"[a-z]", text) print("Lowercase letters found:", lowercase_letters) # Find all uppercase letters uppercase_letters = re.findall(r"[A-Z]", text) print("Uppercase letters found:", uppercase_letters)

In this example, you use the re.findall() function to search for matches in the string "User123, admin42, guestX". The pattern [0-9] matches any digit between 0 and 9, so it finds all individual digits in the text. The pattern [a-z] matches any lowercase letter from "a" to "z", and [A-Z] matches any uppercase letter from "A" to "Z". Each character class is enclosed in square brackets, specifying the range or set of characters to match. These patterns are fundamental in extracting specific types of characters from text.

123456789101112131415161718192021222324252627
import re text = "Hello_123 world! Regex is fun." # \w matches any word character (alphanumeric or underscore) word_chars = re.findall(r"\w", text) print("Word characters (\\w):", word_chars) # \W matches any non-word character non_word_chars = re.findall(r"\W", text) print("Non-word characters (\\W):", non_word_chars) # \b matches word boundaries words = re.findall(r"\b\w+\b", text) print("Words using word boundaries (\\b):", words) # * quantifier: zero or more word characters after 'o' pattern_star = re.findall(r"o\w*", text) print("'o' followed by zero or more word characters (o\\w*):", pattern_star) # + quantifier: one or more word characters after 'R' pattern_plus = re.findall(r"R\w+", text) print("'R' followed by one or more word characters (R\\w+):", pattern_plus) # ? quantifier: 'l' optionally followed by 'e' pattern_question = re.findall(r"le?", text) print("'l' optionally followed by 'e' (le?):", pattern_question)

Here you can see how to use Python's re.findall() function with various regex patterns to extract information from the string "Hello_123 world! Regex is fun.". Here is what each pattern does:

  • \w: The pattern r"\w" matches any word character, which includes letters (both uppercase and lowercase), digits, and the underscore (_). In the given string, this finds every individual word character, such as 'H', 'e', 'l', 'o', '1', '2', '3', and so on.

  • \W: The pattern r"\W" matches any non-word character. This includes spaces, punctuation, and symbols that are not letters, digits, or underscores. In the string, this finds characters like spaces, the exclamation mark (!), and the period (.).

  • \b: The pattern r"\b\w+\b" uses word boundaries (\b) to match complete words. Here, \w+ matches one or more word characters, so this extracts entire words such as 'Hello_123', 'world', 'Regex', 'is', and 'fun' as separate elements.

  • * quantifier: The pattern r"o\w*" matches the character 'o' followed by zero or more word characters. This means it will match 'o' even if it is not followed by any word characters, or it will capture a sequence starting with 'o' and continuing through any following word characters. In the string, this finds 'o_123' (from 'Hello_123') and 'orld' (from 'world').

  • + quantifier: The pattern r"R\w+" matches the character 'R' followed by one or more word characters. This is useful for finding words that start with 'R' and continue with additional word characters. In the string, this finds 'Regex'.

  • ? quantifier: The pattern r"le?" matches the letter 'l' optionally followed by 'e'. The ? quantifier means the preceding character ('e') can appear zero or one time. This pattern will match both 'l' and 'le' wherever they occur in the string.

Each of these patterns highlights a key feature of regular expressions—matching specific character types, boundaries, and repeated elements—making it easier to extract or analyze information from text in Python.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 2
some-alt