python-regexHow to match the beginning of a line with Python regex?
To match the beginning of a line with Python regex, the ^ character is used. This character is known as the "start of line" anchor.
Example code
import re
line = "This is a line of text"
# Match the beginning of the line
match = re.search("^This", line)
if match:
print("Match found!")
else:
print("No match found!")
Output example
Match found!
Code explanation
import re: imports the Python regex moduleline = "This is a line of text": creates a string variablematch = re.search("^This", line): searches for the pattern^Thisin the stringlineif match:: checks if a match was foundprint("Match found!"): prints the message if a match was foundprint("No match found!"): prints the message if no match was found
Helpful links
More of Python Regex
- How to use named groups with regex in Python?
- How to match the end of a line with regex in Python?
- How to perform a zero length match with Python Regex?
- How to match a question mark in Python regex?
- How to ignore case in Python regex?
- How to use negative lookbehind in Python regex?
- How to match a UUID using Python regex?
- How to match a plus sign in Python regex?
- How to get the href attribute value from a regex in Python?
- How to get a group from a regex in Python?
See more codes...