Open In App

How to check if a string starts with a substring using regex in Python?

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 library
import re
 
# define a function
def find(string, sample) :
   
  # check substring present
  # in a string or not
  if (sample in string):
 
      y = "^" + sample
 
      # check if string starts
      # with the substring
      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")
 
 
# Driver code
string = "geeks for geeks makes learning fun" 
sample = "geeks"
 
# function call
find(string, sample)
 
sample = "makes"
 
# function call
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 library
import re
 
# define a function
def find(string, sample) :
   
  # check substring present
  # in a string or not
  if (sample in string):
 
      y = "\A" + sample
 
      # check if string starts
      # with the substring
      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")
 
 
# Driver code
string = "geeks for geeks makes learning fun" 
sample = "geeks"
 
# function call
find(string, sample)
 
sample = "makes"
 
# function call
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.



Previous Article
Next Article

Similar Reads

Python - Check whether a string starts and ends with the same character or not (using Regular Expression)
Given a string. The task is to write a regular expression to check whether a string starts and ends with the same character. Examples: Input : abbaOutput : ValidInput : aOutput : ValidInput : abcOutput : InvalidSolution: The input can be divide into 2 cases: Single character string: All single character strings satisfies the condition that they sta
2 min read
Python Extract Substring Using Regex
Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple and commonly used methods to extract substrings usi
2 min read
Python - Check if string starts with any element in list
While working with strings, their prefixes and suffix play an important role in making any decision. Let’s discuss certain ways in which this task can be performed. Example: String = "GfG is best" Input_lis = ['best', 'GfG', 'good'] Output: True Explanation: 'GfG is best' is present in the list. String = "GfG is best" Input_lis = ['Good', 'Bad', 'N
4 min read
Check if a column starts with given string in Pandas DataFrame?
In this program, we are trying to check whether the specified column in the given data frame starts with specified string or not. Let us try to understand this using an example suppose we have a dataset named student_id, date_of_joining, branch. Example: C/C++ Code #importing library pandas as pd import pandas as pd #creating data frame for student
2 min read
How to check a valid regex string using Python?
A Regex (Regular Expression) is a sequence of characters used for defining a pattern. This pattern could be used for searching, replacing and other operations. Regex is extensively utilized in applications that require input validation, Password validation, Pattern Recognition, search and replace utilities (found in word processors) etc. This is du
6 min read
Python - Check if String Contain Only Defined Characters using Regex
In this article, we are going to see how to check whether the given string contains only a certain set of characters in Python. These defined characters will be represented using sets. Examples: Input: ‘657’ let us say regular expression contains the following characters- (‘78653’) Output: Valid Explanation: The Input string only consists of charac
2 min read
Python | Check if string matches regex list
Sometimes, while working with Python, we can have a problem we have list of regex and we need to check a particular string matches any of the available regex in list. Let's discuss a way in which this task can be performed. Method : Using join regex + loop + re.match() This task can be performed using combination of above functions. In this, we cre
4 min read
Find all the patterns of “1(0+)1” in a given string using Python Regex
A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0’s. Count all such patterns. The patterns are allowed to overlap. Note : It contains digits and lowercase characters only. The string is not necessarily a binary. 100201 is not a valid pattern. Examples: Input : 1101001 Output : 2 Input : 1000
2 min read
The most occurring number in a string using Regex in python
Given a string str, the task is to extract all the numbers from a string and find out the most occurring element of them using Regex Python. It is guaranteed that no two element have the same frequency Examples: Input :geek55of55geeks4abc3dr2 Output :55Input :abcd1def2high2bnasvd3vjhd44Output :2Approach:Extract all the numbers from a string str usi
2 min read
Validate an IP address using Python without using RegEx
Given an IP address as input, the task is to write a Python program to check whether the given IP Address is Valid or not without using RegEx. What is an IP (Internet Protocol) Address? Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. An IP address (version 4) consists
2 min read
Practice Tags :