作为一项任务,我面临的问题是:
Given an input string similar to the below, craft a regular expression pattern to match and extract the date, time, and temperature in groups and return this pattern. Samples given below.
Date: 12/31/1999 Time: 11:59 p.m. Temperature: 44 F
Date: 01/01/2000 Time: 12:01 a.m. Temperature: 5.2 C
所以我打开了regex101和created this pattern which tests correctly:
def q6(strng):
import re
pattern = '((?<=Date: )\d{1,2}\/\d{1,2}\/\d{4})|((?<=Time: )?\d{1,2}:\d{1,2} ?[pPaA].?[mM].?)|((?<=Temperature: )\d{1,3}.?\d{1,3} ?[CF])'
print(re.findall(pattern, strng))
return pattern
q6("Date: 12/31/1999 Time: 11:59 p.m. Temperature: 44 F")
q6("Date: 01/01/2000 Time: 12:01 a.m. Temperature: 5.2 C")
但在python中,该模式似乎给出了一个有缺陷的答案:
[('12/31/1999', '', ''), ('', '11:59 p.m.', ''), ('', '', '44 F')]
[('01/01/2000', '', ''), ('', '12:01 a.m.', ''), ('', '', '5.2 C')]
您可以在返回的元组中看到额外的空项。该问题将通过程序进行评分,如果您注意到该问题要求返回模式,而不是结果,则不可能进行修剪
我只是使用了错误的正则表达式匹配函数,还是我做错了什么
您应该在不希望捕获的括号中添加
?:
:(?:.....)|(?:....)|(?:...)
TL;DR:您引用了问题最后一句话命名了一个解决方案:^{} function 😉️
打印的元组似乎是正确的结果
从文件^{} 中:
我用粗体突出显示了适合您案例的部分
分析需求或验收标准
只需将您的任务(文本)按
and
分割即可获得以下3个要求:分解成子任务,任务或问题变得容易解决。此外,这些步骤将引导您找到解决方案
这种解决问题的策略被称为divide and conquer
解决方案的线索
现在试着一步一步地解,从(1)开始,然后(2),最后(3)
groups
(所有3个部分放在括号内)可以提取(一次提取所有部分,但仅当给定字符串与模式匹配时)对不起,我没有给你提供完美的解决方案。但你们很接近。据我所知,这些线索会让你达到目的
我给了你一个循序渐进的食谱,外加关键字,你可以用它来search on Stackoverflow:
[python] regex extract groups
它们都在您指定的任务中:
根据我的手工艺经验
分析问题,确定关键词,澄清宽泛/模糊的规范,以便您能够从80%的设计软件中研究和收集成分。而烹饪和编码占了剩下的20%
相关问题 更多 >
编程相关推荐