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^This
in the stringline
if 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 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 perform a zero length match with Python Regex?
- How to match a UUID using Python regex?
- How to match a year with Python Regex?
- How to match a URL using Python regex?
- How to remove numbers from a string using Python regex?
- How to replace all using Python regex?
- How to get all matches from a regex in Python?
See more codes...