Python正則表示式查詢一個大寫字母后跟小寫字母的序列


當需要使用正則表示式查詢一個大寫字母后跟小寫字母的序列時,定義了一個名為“match_string”的方法,該方法使用“search”方法來匹配正則表示式。在方法外部,定義了字串,並透過傳遞字串來呼叫該方法。

示例

以下是相同內容的演示

import re

def match_string(my_string):

   pattern = '[A-Z]+[a-z]+$'

   if re.search(pattern, my_string):
      return('The string meets the required condition \n')
   else:
      return('The string doesnot meet the required condition \n')

print("The string is :")
string_1 = "Python"
print(string_1)
print(match_string(string_1))

print("The string is :")
string_2 = "python"
print(string_2)
print(match_string(string_2))

print("The string is :")
string_3 = "PythonInterpreter"
print(string_3)
print(match_string(string_3))

輸出

The string is :
Python
The string meets the required condition
The string is :
python
The string doesn’t meet the required condition
The string is :
PythonInterpreter
The string meets the required condition

解釋

  • 匯入所需的包。

  • 定義了一個名為“match_string”的方法,該方法將字串作為引數。

  • 它使用“search”方法檢查字串中是否存在特定的正則表示式。

  • 在方法外部,定義了一個字串,並在控制檯上顯示。

  • 透過傳遞此字串作為引數來呼叫該方法。

  • 輸出顯示在控制檯上。

更新於: 2021年9月20日

721 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.