re.match is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using ^ in the pattern.

As the re.match documentation says:

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Note: If you want to locate a match anywhere in string, use search() instead.

re.search searches the entire string, as the documentation says:

Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

So if you need to match at the beginning of the string, or to match the entire string use match. It is faster. Otherwise use search.

The documentation has a specific section for match vs. search that also covers multiline strings:

Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).

Note that match may differ from search even when using a regular expression beginning with '^': '^' matches only at the start of the string, or in MULTILINE mode also immediately following a newline. The “match” operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optional pos argument regardless of whether a newline precedes it.

Now, enough talk. Time to see some example code:

# example code:
string_with_newlines = """something
someotherthing"""

import re

print re.match('some', string_with_newlines) # matches
print re.match('someother', 
               string_with_newlines) # won't match
print re.match('^someother', string_with_newlines, 
               re.MULTILINE) # also won't match
print re.search('someother', 
                string_with_newlines) # finds something
print re.search('^someother', string_with_newlines, 
                re.MULTILINE) # also finds something

m = re.compile('thing$', re.MULTILINE)

print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines, 
               re.MULTILINE) # also matches
Answer from nosklo on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › re.html
re — Regular expression operations
However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it’s highly recommended that you use raw strings for all but the simplest expressions. ... Used to indicate a set of characters. In a set: Characters can be listed individually, e.g. [amk] will match 'a', 'm', or 'k'.
🌐
GeeksforGeeks
geeksforgeeks.org › python › re-match-in-python
re.match() in Python - GeeksforGeeks
1 month ago - The re.match() method in Python is used to check whether a regular expression pattern matches the beginning of a string.
Discussions

How do I return a string from a regex match in python? - Stack Overflow
I am running through lines in a text file using a python script. I want to search for an img tag within the text document and return the tag as text. When I run the regex re.match(line) it returns... More on stackoverflow.com
🌐 stackoverflow.com
python - How can I make a regex match the entire string? - Stack Overflow
@smart really only needs to put the $, since re.match automatically assumes ^ on the regex. 2017-07-21T19:31:21.913Z+00:00 ... Years using regex and I never knew what were the "^" and "+$". A greater explanation is in here: stackoverflow.com/questions/34292024/… 2020-11-27T15:26:49.017Z+00:00 ... Save this answer. ... Show activity on this post. Since Python ... More on stackoverflow.com
🌐 stackoverflow.com
How do you use re.match() ? Python
Can you give an example of a string you're trying to match? More on reddit.com
🌐 r/learnprogramming
8
1
August 16, 2022
`re.match()`: raise exception if string doesn't match? - Ideas - Discussions on Python.org
Is there any sense in providing a version of re.match() that raises an exception, rather than returning None, when the string doesn’t match the pattern? It’s one of the few places where I find myself repeatedly writing if match is None: rather than except ValueError: or similar. Thanks! More on discuss.python.org
🌐 discuss.python.org
1
December 28, 2021
Top answer
1 of 10
688

re.match is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using ^ in the pattern.

As the re.match documentation says:

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Note: If you want to locate a match anywhere in string, use search() instead.

re.search searches the entire string, as the documentation says:

Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

So if you need to match at the beginning of the string, or to match the entire string use match. It is faster. Otherwise use search.

The documentation has a specific section for match vs. search that also covers multiline strings:

Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).

Note that match may differ from search even when using a regular expression beginning with '^': '^' matches only at the start of the string, or in MULTILINE mode also immediately following a newline. The “match” operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optional pos argument regardless of whether a newline precedes it.

Now, enough talk. Time to see some example code:

# example code:
string_with_newlines = """something
someotherthing"""

import re

print re.match('some', string_with_newlines) # matches
print re.match('someother', 
               string_with_newlines) # won't match
print re.match('^someother', string_with_newlines, 
               re.MULTILINE) # also won't match
print re.search('someother', 
                string_with_newlines) # finds something
print re.search('^someother', string_with_newlines, 
                re.MULTILINE) # also finds something

m = re.compile('thing$', re.MULTILINE)

print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines, 
               re.MULTILINE) # also matches
2 of 10
147

search ⇒ find something anywhere in the string and return a match object.

match ⇒ find something at the beginning of the string and return a match object.

🌐
AppSignal
blog.appsignal.com › home › python › python regex: how to use re.search, re.match, and re.findall
Python Regex: How to Use re.search, re.match, and re.findall | AppSignal Blog
January 15, 2025 - Learn Python regex step by step: pattern basics, the re module's search, match, and findall functions, real-world examples, and performance tips.
🌐
W3Schools
w3schools.com › python › python_regex.asp
Python RegEx
Python has a built-in package called re, which can be used to work with Regular Expressions. ... You can add flags to the pattern when using regular expressions. A special sequence is a \ followed by one of the characters in the list below, and has a special meaning: A set is a set of characters inside a pair of square brackets [] with a special meaning: The findall() function returns a list containing all matches.
🌐
Built In
builtin.com › articles › python-re-match
Python re.match() and re.sub() Explained | Built In
re.match() is a function in Python that searches for a match only at the beginning of the string. If the match is found at the start of the string, it returns a match object. Otherwise, it returns None.
Find elsewhere
🌐
TestDriven.io
testdriven.io › tips › 421e050b-176b-4a72-a8b5-6ad5f185b86a
Tips and Tricks - Difference between re.search and re.match in Python? | TestDriven.io
re.match() searches for matches from the beginning of a string while re.search() searches for matches anywhere in the string. ... import re claim = 'People love Python.' print(re.search(r'Python', claim).group()) # => Python print(re.match(...
🌐
Mimo
mimo.org › glossary › python › regex-regular-expressions
Mimo: The coding platform you need to learn Web Development, Python, and more.
It's best practice to define regex patterns using raw strings by prefixing the string with an r (e.g., r"\d+") to prevent backslashes from being misinterpreted. 1. Finding the First Match with re.search(): This function returns a match object if the pattern is found, and None otherwise.
🌐
Python documentation
docs.python.org › 3 › howto › regex.html
Regular expression HOWTO — Python 3.14.7 documentation
Regular expressions (called REs, ... through the re module. Using this little language, you specify the rules for the set of possible strings that you want to match; ......
🌐
Google
developers.google.com › google for education › python › python regular expressions
Python Regular Expressions | Python Education | Google for Developers
In Python a regular expression ... and searches for that pattern within the string. If the search is successful, search() returns a match object or None otherwise....
🌐
Reddit
reddit.com › r/learnprogramming › how do you use re.match() ? python
r/learnprogramming on Reddit: How do you use re.match() ? Python
August 16, 2022 -

I’ve been looking at tutorials and I can’t figure out why I can’t get it to work, I’m trying to see if a substring matches a certain format but the output is incorrect.

re.match(‘[A-Z],[A-Z] $’ , s)

Is this not how to set it up?

🌐
Medium
medium.com › @ebojacky › the-very-bare-minimum-essentials-for-regular-expressions-in-python-54e78c10b649
The Very Bare Minimum Essentials for Regular Expressions in Python | by Ebo Jackson | Medium
June 2, 2025 - Regular expressions (regex) in Python are a powerful tool for pattern matching, text manipulation, and data extraction. The re module provides a robust framework for working with regex, enabling developers to handle tasks like validation, parsing, ...
🌐
Squash
squash.io › how-to-use-regex-to-match-any-character-in-python
How to Use Regex to Match Any Character in Python
November 2, 2023 - In Python regex, the dot metacharacter (.) is used to match any character except a newline. It represents a single character that can be any character in the input string.
🌐
LeetCode
leetcode.com › problems › regular-expression-matching
Regular Expression Matching - LeetCode
Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa". ... Input: s = "aa", p = "a*" Output: true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
🌐
Python.org
discuss.python.org › ideas
`re.match()`: raise exception if string doesn't match? - Ideas - Discussions on Python.org
December 28, 2021 - Is there any sense in providing a version of re.match() that raises an exception, rather than returning None, when the string doesn’t match the pattern? It’s one of the few places where I find myself repeatedly writing if match is None: rather than except ValueError: or similar. Thanks!
🌐
USAVPS
usavps.com › home › blog › python tutorial: re — regular expression operations
Python Tutorial: re — Regular Expression Operations - USAVPS
March 18, 2026 - Regular expressions are an essential tool for string manipulation in Python. The re module provides a variety of functions to search, match, and replace strings based on defined patterns.
🌐
Reddit
reddit.com › r/regex › regex match works in regex101.com (in python) and doesnt work when i try in python terminal
r/regex on Reddit: Regex match works in regex101.com (in python) and doesnt work when i try in python terminal
June 4, 2020 -

Link to the example

So I'm trying to make a regex that matches from opening to closing '<>' brackets. So I've figured out that '(<[^<^>])*(>)*' should work pretty well, so I've tried it in regex101.com, and it worked perfectly (matched <pair<int,string>> in 'List<pair<int,string>>') but when I try it in Python terminal (v3.8 if it matters), it matches only the inside brackets (re.findall returns [('', ''), ('', ''), ('', ''), ('', ''), ('<int,string', '>'), ('', '')]). I've used the same expression, and the same flags (multiline).

Does anyone know what could cause that to be different?

Top answer
1 of 2
3

Curious, have you checked out the code generator on regex101?

https://regex101.com/r/FYmNPx/1/codegen?language=python

2 of 2
3

regex101 only emulates the functionality, not an exact representation of python

I don't think it know the various rules of findall - when you use capture groups, result will depend on the number of capture groups used

In this case I don't think you are interested in capture groups, you only want the overall match. So, use non-capturing groups

>>> s = 'List<pair<int,string>>'
>>> re.findall(r'(?:<[^<>]+)+>+', s)
['<pair<int,string>>']

If capture groups are used, each element of output will be a tuple of strings of all the capture groups. Text matched by the RE outside of capture groups won't be present in the output list. If there is only one capture group, tuple won't be used and each element will be the matched portion of that capture group.

>>> re.findall(r'ab*c', 'abc ac adc abbc xabbbcz bbb bc abbbbbc')
['abc', 'ac', 'abbc', 'abbbc', 'abbbbbc']
>>> re.findall(r'a(b*)c', 'abc ac adc abbc xabbbcz bbb bc abbbbbc')
['b', '', 'bb', 'bbb', 'bbbbb']

>>> re.findall(r'(x*):(y*)', 'xx:yyy x: x:yy :y')
[('xx', 'yyy'), ('x', ''), ('x', 'yy'), ('', 'y')]

If you use regex third party module, you can do it for any number of nesting:

>>> regex.findall(r'<(?:[^<>]++|(?0))++>', 'List<pair<int,string>> <a<b<c<d>>>>')
['<pair<int,string>>', '<a<b<c<d>>>>']

See my book (https://github.com/learnbyexample/py_regular_expressions/blob/master/py_regex.md#recursive-matching) for explanation

🌐
7-Zip Documentation
documentation.help › python 3.7.3 › re — regular expression operations
re — Regular expression operations | Python 3.7.3 Documentation
March 25, 2019 - However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it’s highly recommended that you use raw strings for all but the simplest expressions. ... Used to indicate a set of characters. In a set: Characters can be listed individually, e.g. [amk] will match 'a', 'm', or 'k'.