如何匹配正则表达式模式并返回捕获的组,而不包括未捕获组的空字符串?

2024-09-30 22:10:07 发布

您现在位置:Python中文网/ 问答频道 /正文

作为一项任务,我面临的问题是:

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')]

您可以在返回的元组中看到额外的空项。该问题将通过程序进行评分,如果您注意到该问题要求返回模式,而不是结果,则不可能进行修剪

我只是使用了错误的正则表达式匹配函数,还是我做错了什么


Tags: andthetoredatereturntime模式
2条回答

您应该在不希望捕获的括号中添加?:(?:.....)|(?:....)|(?:...)

TL;DR:您引用了问题最后一句话命名了一个解决方案:^{} function😉️

打印的元组似乎是正确的结果

从文件^{}中:

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

Changed in version 3.7: Non-empty matches can now start just after a previous empty match.

我用粗体突出显示了适合您案例的部分

分析需求或验收标准

只需将您的任务(文本)按and分割即可获得以下3个要求:

  1. 创建一个正则表达式模式以匹配
  2. 提取组中的日期时间温度
  3. 返回此模式

分解成子任务,任务或问题变得容易解决。此外,这些步骤将引导您找到解决方案

这种解决问题的策略被称为divide and conquer

解决方案的线索

现在试着一步一步地解,从(1)开始,然后(2),最后(3)

  1. (a) 将一个{}gex字符串({})和(b){}构造成一个模式,以(c){}
  2. (如果匹配,则)groups(所有3个部分放在括号内)可以提取(一次提取所有部分,但仅当给定字符串与模式匹配时)
  3. (澄清)具体返回什么(期望对象的类型:模式或正则表达式作为字符串)

对不起,我没有给你提供完美的解决方案。但你们很接近。据我所知,这些线索会让你达到目的

我给了你一个循序渐进的食谱,外加关键字,你可以用它来search on Stackoverflow

[python] regex extract groups

它们都在您指定的任务中:

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.

根据我的手工艺经验

分析问题,确定关键词,澄清宽泛/模糊的规范,以便您能够从80%的设计软件中研究和收集成分。而烹饪和编码占了剩下的20%

相关问题 更多 >