使用正则表达式检查字符串是否仅包含定义的字符的 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 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.