How to Check if a String Starts with a Substring Using Regex in Python? (original) (raw)

Last Updated : 4 Nov, 2025

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.

Python `

import re s = "geeks for geeks makes learning fun" res = "geeks"

if re.match(res, s): print("True") else: print("False")

`

**Explanation:

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.

Python `

import re s = "geeks for geeks makes learning fun" res = "geeks"

p = "^" + res if re.search(p, s): print("True") else: print("False")

`

**Explanation:

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.

Python `

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")

`

**Explanation: