使用正則表示式檢查字串是否僅包含定義的字元的 Python 程式


當需要使用正則表示式檢查給定字串是否包含特定字元時,會定義一個正則表示式模式,並將字串應用於遵循此模式。

示例

以下是相同內容的演示

import re
def check_string(my_string, regex_pattern):

   if re.search(regex_pattern, my_string):
      print("The string contains the defined characters only")
   else:
      print("The doesnot string contain the defined characters")

regex_pattern = re.compile('^[Python]+$')

my_string_1 = 'Python'
print("The string is :")
print(my_string_1)
check_string(my_string_1 , regex_pattern)

my_string_2 = 'PythonInterpreter'
print("\nThe string is :")
print(my_string_2)
check_string(my_string_2, regex_pattern)

輸出

The string is :
Python
The string contains the defined characters
The string is :
PythonInterpreter
The doesn’t string contain the defined characters

解釋

  • 匯入所需的包。

  • 定義了一個名為“check_string”的方法,它以字串和正則表示式作為引數。

  • 呼叫“search”方法並檢查字串中是否存在特定字元集。

  • 在方法外部,在正則表示式上呼叫“compile”方法。

  • 定義字串並在控制檯上顯示。

  • 透過傳遞此字串來呼叫該方法。

  • 在控制檯上顯示輸出。

更新於: 2021年9月20日

394 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告