首页 > 解决方案 > 如何通过这个正则表达式搜索挑战?

问题描述

我无法通过此代码挑战:

正则表达式搜索挑战 使用下面的 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')

我真的没有从程序中得到任何反馈。它只是告诉我我失败了,没有错误消息。

标签: pythonregex

解决方案


如果我运行你的代码,我会收到一个错误告诉我

pattern = ex1 + ex2 + ex3 + ex4

失败,因为不支持添加匹配对象。

挑战可能是试图教您在正则表达式中使用字符集。基本上,您不需要ex1,ex2等。您只需在pattern变量中定义正则表达式模式并将其提供给re.findall.

我还推荐使用RegExrregex101等工具来试验正则表达式。


推荐阅读