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 theremodule 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 perform a zero length match with Python Regex?
- How to match whitespace in Python regex?
- How to ignore case in Python regex?
- How to get all matches from a regex in Python?
- How to make a case insensitive match with Python regex?
- How to match a URL path using Python regex?
- How to get a group from a regex in Python?
- How to match a plus sign in Python regex?
See more codes...