How to Check if a String Starts with a Substring Using Regex in Python?
Given a string and a substring, the task is to check whether the string starts with the specified substring or not using Regex in Python.
For example:
String: "geeks for geeks makes learning fun"
Substring: "geeks"
Output: True
Let’s explore different regex-based methods to check if a string starts with a given substring in Python.
Using re.match()
"re.match()" method checks if a string starts with a specific substring. It automatically matches only at the beginning of the string, so no special anchor is required.
import re
s = "geeks for geeks makes learning fun"
res = "geeks"
if re.match(res, s):
print("True")
else:
print("False")
Output
True
Explanation:
- re.match(substring, string) checks if the string starts with the given pattern.
- It returns a match object if found; otherwise, None.
Using re.search() with “^” Anchor
The ^ (caret) metacharacter in regex is used to match text only at the start of the string. We can use it with re.search() to check if the string begins with the given substring.
import re
s = "geeks for geeks makes learning fun"
res = "geeks"
p = "^" + res
if re.search(p, s):
print("True")
else:
print("False")
Output
True
Explanation:
- "^" ensures that the match happens only at the start of the string.
- re.search() scans the text for a match, but since ^ restricts it to the start, it works just like re.match().
Using re.search() with “\A” Anchor
'\A' metacharacter also matches only at the beginning of the string, regardless of multiline mode. It behaves similarly to ^ but is more strict, ensuring it only checks the very start of the entire string.
import re
s = "geeks for geeks makes learning fun"
res = "geeks"
p = r"\A" + res
if re.search(p, s):
print("True")
else:
print("False")
Output
True
Explanation:
- \A checks only the absolute start of the string (not each line).
- Useful when working with multiline strings and you want to ensure the check applies to the full string, not each line.