All categories
    PythonAdvanced

    Regular Expressions

    Python regular expressions with the re module: search, findall, sub, and split to match and transform text patterns.

    01Search for a pattern

    main.py
    import re
    text = "Contact: john@example.com"
    match = re.search(r"\w+@\w+\.\w+", text)
    print(match.group())
    Output
    john@example.com

    02Find all matches

    main.py
    import re
    text = "Call 123 or 456 today"
    numbers = re.findall(r"\d+", text)
    print(numbers)
    Output
    ['123', '456']

    03Replace with sub

    main.py
    import re
    text = "hello world"
    print(re.sub(r"o", "0", text))
    Output
    hell0 w0rld

    04Split on a pattern

    main.py
    import re
    text = "a1b2c3d"
    print(re.split(r"\d", text))
    Output
    ['a', 'b', 'c', 'd']