📌  相关文章
📜  如何在Python中使用正则表达式检查字符串是否以子字符串开头?

📅  最后修改于: 2022-05-13 01:55:45.388000             🧑  作者: Mango

如何在Python中使用正则表达式检查字符串是否以子字符串开头?

先决条件: Python中的正则表达式

给定一个字符串str,任务是检查一个字符串是否以给定的子字符串开头或不使用正则表达式。

例子:

Input: String: "geeks for geeks makes learning fun" 
       Substring: "geeks" 
Output: True 
Input: String: "geeks for geeks makes learning fun" 
       Substring: "makes" 
Output: False

方法一:
在这里,我们首先检查字符串中是否存在给定的子字符串,如果是,那么我们使用re 库search()函数和元字符“^”。此元字符检查给定字符串是否以提供的子字符串开头。

下面是上述方法的实现:

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)


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)


输出:

string starts with the given substring
string doesn't start with the given substring

方法二:
在这里,我们首先检查字符串中是否存在给定的子字符串,如果是,那么我们使用re 库search()函数以及元字符“\A”。此元字符检查给定字符串是否以提供的子字符串开头。


下面是上述方法的实现:

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)

输出:

string starts with the given substring
string doesn't start with the given substring