python-regexHow to do an exact match with regex in Python?
To do an exact match with regex in Python, you can use the re.match()
function. This function takes a regular expression pattern and a string as arguments and returns a match object if there is a match.
Example code
import re
pattern = r"Hello"
string = "Hello World"
match = re.match(pattern, string)
if match:
print("Match found:", match.group())
else:
print("No match found")
Output example
Match found: Hello
Code explanation
import re
: imports there
module which contains there.match()
functionpattern = r"Hello"
: defines the regular expression pattern to matchstring = "Hello World"
: defines the string to match againstmatch = re.match(pattern, string)
: calls there.match()
function with the pattern and string as argumentsif match:
: checks if a match was foundprint("Match found:", match.group())
: prints the matched stringelse:
: runs if no match was foundprint("No match found")
: prints a message if no match was found
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a URL path using Python regex?
- How to match a year with Python Regex?
- How to match a UUID using Python regex?
- How to match whitespace in Python regex?
- How to remove numbers from a string using Python regex?
- How to replace in a file using Python regex?
- How to replace all using Python regex?
- How to perform a zero length match with Python Regex?
See more codes...