Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Regex in Python

Regex in Python

Regular Expressions (RegEx) in Python

Regular expressions (RegEx) are powerful tools used for matching patterns in strings. Python provides the re module for working with regular expressions.


Basic Functions in re Module

Here are the most commonly used functions in the re module for working with regular expressions:

  1. re.match()

    • Determines if the regular expression matches at the beginning of the string.

    import reresult = re.match(r"Hello", "Hello, world!")if result:    print("Match found!")else:    print("No match.")
  2. re.search()

    • Searches the string for a match anywhere in the string. It returns the first match it finds.

    import reresult = re.search(r"world", "Hello, world!")if result:    print("Match found!")else:    print("No match.")
  3. re.findall()

    • Returns all non-overlapping matches of the regular expression in the string as a list.

    import reresult = re.findall(r"\d+", "My number is 123 and my friend's number is 456.")print(result)  # Output: ['123', '456']
  4. re.finditer()

    • Returns an iterator yielding match objects for all non-overlapping matches of the regular expression in the string.

    import reresult = re.finditer(r"\d+", "My number is 123 and my friend's number is 456.")for match in result:    print(match.group())  # Output: 123, 456
  5. re.sub()

    • Replaces occurrences of the pattern in the string with a replacement string.

    import reresult = re.sub(r"\d+", "X", "My number is 123 and my friend's number is 456.")print(result)  # Output: My number is X and my friend's number is X.
  6. re.split()

    • Splits the string at occurrences of the pattern.

    import reresult = re.split(r"\s+", "This  is    a test.")print(result)  # Output: ['This', 'is', 'a', 'test.']

Regular Expression Syntax

Here are some key components of regular expressions that you can use with the re module:

  • . (dot): Matches any character except a newline.

    import reresult = re.search(r"a.b", "acb")  # Matches "acb"
  • ^: Matches the beginning of the string.

    import reresult = re.search(r"^Hello", "Hello, world!")  # Matches
  • $: Matches the end of the string.

    import reresult = re.search(r"world!$", "Hello, world!")  # Matches
  • [] (Character class): Matches any one of the characters inside the brackets.

    import reresult = re.search(r"[aeiou]", "Hello")  # Matches any vowel
  • | (OR operator): Matches either the pattern on the left or the pattern on the right.

    import reresult = re.search(r"cat|dog", "I have a dog.")  # Matches "dog"
  • * (Zero or more occurrences): Matches zero or more repetitions of the preceding pattern.

    import reresult = re.search(r"ab*", "a")  # Matches "a"
  • + (One or more occurrences): Matches one or more repetitions of the preceding pattern.

    import reresult = re.search(r"ab+", "abb")  # Matches "abb"
  • ? (Zero or one occurrence): Matches zero or one repetition of the preceding pattern.

    import reresult = re.search(r"ab?", "a")  # Matches "a"
  • {n}: Matches exactly n occurrences of the preceding pattern.

    import reresult = re.search(r"a{3}", "aaab")  # Matches "aaa"
  • \d: Matches any digit (equivalent to [0-9]).

    import reresult = re.search(r"\d", "abc123")  # Matches "1"
  • \D: Matches any non-digit character (equivalent to [^0-9]).

    import reresult = re.search(r"\D", "abc123")  # Matches "a"
  • \w: Matches any alphanumeric character (equivalent to [a-zA-Z0-9_]).

    import reresult = re.search(r"\w", "abc123")  # Matches "a"
  • \W: Matches any non-alphanumeric character.

    import reresult = re.search(r"\W", "abc123!")  # Matches "!"
  • \s: Matches any whitespace character (space, tab, newline).

    import reresult = re.search(r"\s", "abc 123")  # Matches the space between "abc" and "123"
  • \S: Matches any non-whitespace character.

    import reresult = re.search(r"\S", "abc 123")  # Matches "a"
  • () (Grouping): Groups patterns together, enabling operations like alternation and repetition on the entire group.

    import reresult = re.search(r"(ab)+", "ababab")  # Matches "ababab"

Example: Extracting Email Addresses

You can use regular expressions to find email addresses in a string.

import retext = "Contact us at support@example.com or sales@example.co.uk."emails = re.findall(r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+", text)print(emails)  # Output: ['support@example.com', 'sales@example.co.uk']

Conclusion

Regular expressions are a powerful tool for string pattern matching and manipulation in Python. They allow you to search, match, and manipulate strings based on complex patterns. The re module is flexible and supports a wide range of use cases, from simple pattern matching to complex string parsing tasks.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql