python - 如何通过这个正则表达式搜索挑战?
问题描述
我无法通过此代码挑战:
正则表达式搜索挑战 使用下面的 Python 字符串使用您创建的正则表达式执行搜索。
search_string='''这是一个字符串,用于搜索正则表达式,如正则表达式或正则表达式或正则:表达式或正则&表达式'''</p>
编写一个正则表达式,找出所有出现的: a. 正则表达式 B. 正则表达式 C. 正则:表达式 d. search_string 中的正则和表达式
将正则表达式分配给名为模式的变量
使用 re 包中的 findall() 方法确定 search_string 中是否存在
将 findall() 方法的结果分配给名为 match1 的变量
如果 match1 不是 None:将用于执行匹配的模式打印到控制台,后跟单词“matched”</p>
否则:将用于执行匹配的模式打印到控制台,后跟“不匹配”字样</p>
这是我的代码:
import re
#The string to search for the regular expression occurrence (This is provided to the student)
search_string = '''This is a string to search for a regular expression like regular expression or
regular-expression or regular:expression or regular&expression'''
#1. Write a regular expression that will find all occurrences of:
# a. regular expression
# b. regular-expression
# c. regular:expression
# d. regular&expression
# in search_string
#2. Assign the regular expression to a variable named pattern
ex1 = re.search('regular expression', search_string)
ex2 = re.search('regular-expression', search_string)
ex3 = re.search('regular:expression', search_string)
ex4 = re.search('regular&expression', search_string)
pattern = ex1 + ex2 + ex3 + ex4
#1. Using the findall() method from the re package determine if there are occurrences in search_string
#. Assign the outcome of the findall() method to a variable called match1
#2. If match1 is not None:
# a. Print to the console the pattern used to perform the match, followed by the word 'matched'
#3. Otherwise:
# a. Print to the console the pattern used to perform the match, followed by the words 'did not match'
match1 = re.findall(pattern, search_string)
if match1 != None:
print(pattern + 'matched')
else:
print(pattern + 'did not match')
我真的没有从程序中得到任何反馈。它只是告诉我我失败了,没有错误消息。
解决方案
推荐阅读
- modx - MODX GetResources 显示 unpub_date
- python - 为什么我在 Windows PC 中启动虚拟环境时收到此消息
- sql - 我们是否应该将单向的一对多关系分解为 JoinTable
- css - 无法使用 Angular flex 布局设置 ngx-quill 编辑器的高度
- android - 使用 Fragment 的 Android Jetpack 分页:适配器未收到回调
- excel - 复杂的查找和替换
- linux - Linux Bash 中的一行命令
- sql - 如何选择具有子字符串的行
- python-3.x - tensorflow api 2.0 张量对象仅在启用急切执行时才可迭代。要迭代此张量,请使用 tf.map_fn
- qt - QML滚动区域,列堆叠项目在彼此之上