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 match a plus sign in Python regex?
- How to match a UUID using Python regex?
- How to match a question mark in Python regex?
- How to match HTML tags with regex in Python?
- How to match a URL using Python regex?
- How to replace a certain group using Python regex?
- How to validate an IP using Python regex?
- How to replace in a file using Python regex?
- How to get a number from a string with regex in Python?
- How to remove special characters using Python regex?
See more codes...