Prerequisite: Regular Expression in Python
Given a string str, the task is to check if a string starts with a given substring or not using regular expression in Python.
Examples:
Input: String: "geeks for geeks makes learning fun"
Substring: "geeks"
Output: True
Input: String: "geeks for geeks makes learning fun"
Substring: "makes"
Output: False
Check if a string starts with a substring using regex
Here, we first check a given substring present in a string or not if yes then we use search() function of re library along with metacharacter “^”. This metacharacter checks for a given string starts with substring provided or not.
Below is the implementation of the above approach:
Python3
import re
def find(string, sample) :
if (sample in string):
y = "^" + sample
x = re.search(y, string)
if x :
print ( "string starts with the given substring" )
else :
print ( "string doesn't start with the given substring" )
else :
print ( "entered string isn't a substring" )
string = "geeks for geeks makes learning fun"
sample = "geeks"
find(string, sample)
sample = "makes"
find(string, sample)
|
Output:
string starts with the given substring
string doesn't start with the given substring
Time complexity : O(n), where n is the length of the input string.
Space complexity : O(1) as it only uses a fixed amount of memory, regardless of the size of the input string.
if a string starts with a substring
Here, we first check a given substring present in a string or not if yes then we use search() function of re library along with metacharacter “\A”. This metacharacter checks for a given string starts with substring provided or not.
Below is the implementation of the above approach:
Python3
import re
def find(string, sample) :
if (sample in string):
y = "\A" + sample
x = re.search(y, string)
if x :
print ( "string starts with the given substring" )
else :
print ( "string doesn't start with the given substring" )
else :
print ( "entered string isn't a substring" )
string = "geeks for geeks makes learning fun"
sample = "geeks"
find(string, sample)
sample = "makes"
find(string, sample)
|
Output:
string starts with the given substring
string doesn't start with the given substring
Time complexity : O(n), where n is the length of the input string.
Space complexity : O(1) as it only uses a fixed amount of memory, regardless of the size of the input string.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Aug, 2023
Like Article
Save Article