我不能通过这个代码挑战:
正则表达式搜索挑战使用下面的Python字符串使用您创建的正则表达式执行搜索。 search _ string =‘’这是一个字符串,用于搜索正则表达式、正则表达式或正则表达式:表达式或正则表达式‘。 编写一个正则表达式,该表达式将在search_string中找到所有出现的正则表达式b.正则表达式c.正则:表达式d正则表达式 将正则表达式赋值给名为模式的变量。 使用re包中的findall()方法确定search_string中是否出现了 将findall()方法的结果分配给一个名为match1的变量 如果match1不是None: a.将用于执行匹配的模式打印到控制台,后面跟着单词“匹配” 否则:将用于执行匹配的模式打印到控制台,后面跟着单词“不匹配”。
这是我的代码:
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')我真的没有从节目中得到任何反馈。它只是告诉我,我失败了,没有错误信息。
发布于 2019-08-13 00:36:58
嘿,我知道这有点晚了,但我现在正经历同样的挑战,所以我想我应该帮助如何通过检查点。
因此,"tfw“在使用字符集时是绝对正确的。实际上只有1行代码.
#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因此,基本上,最简单的方法是指定每个字符集的表达式。看起来像这样..。
pattern = "regular[ -:&]expression"通过这样做,我们可以在同一个名为pattern的变量中添加空格、-、:和&。现在你的第二部分。
#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')无论如何,希望这能帮助其他可能只需要在正确的方向上稍微推动一下的人。我总是发现更容易看到代码在做什么,而不是被告知代码应该如何在没有什么方向的情况下:D
发布于 2020-08-09 21:12:27
将表达式更改为pattern = regular[ -:&]expression
https://stackoverflow.com/questions/55660329
复制相似问题