gpt4 book ai didi

python - 在匹配模式之前匹配单词不定次数

转载 作者:行者123 更新时间:2023-12-01 09:00:56 25 4
gpt4 key购买 nike

可能的输入示例:

'Starts in 09h 52m 56s'
'Ends in 00h 33m 13s'

上面两个输入的输出为:

['Starts', '09', '52', '56']
['Ends', '00', '33', '13']

下面是一种可行的模式:

(Starts|Ends) in ([0-9]{2})h ([0-9]{2})m ([0-9]{2})s

不幸的是,它输出的所有内容如下:

[('Ends', '00', '46', '34')]

而不是:

['Ends', '00', '46', '34']

然而,更重要的是,我想让正则表达式更加简洁,而不是必须重复 ([0-9]{2}) 三次。

我尝试使用(Starts|Ends)|([0-9]{2})[h|m|s],但这输出以下内容:

[('Ends', ''), ('', '04'), ('', '20'), ('', '41')]

同样,我正在寻找的输出很简单:

['Ends', '00', '33', '13']

根据要求,这是我的代码:

regex_time_left = re.compile(r'(Starts|Ends) in ([0-9]{2})h ([0-9]{2})m ([0-9]{2})s')
for product_page in indi_product_urls:
time_left = ff.find_elements(By.CSS_SELECTOR, 'span[id*=deal_expiry_timer_]')
if len(time_left) > 0:
time_left = regex_time_left.findall(time_left[0].text) # [('Ends', '00', '32', '31')]
starts_ends = time_left[0][0]
hours = time_left[0][1]
minutes = time_left[0][2]
seconds = time_left[0][3]

有什么想法吗?

最佳答案

试试这个代码!

您可以使用regex(在Python中导入re库)并提取小时、分钟和秒值。这里 d{2} 表示 2 位整数值,因为小时/分钟/秒值始终为 2 位数字。

代码:

import re

start = 'Starts in 09h 52m 56s'
end = 'Ends in 00h 33m 13s'

matchObj = re.match( r'(?:Starts|Ends)[ ]in[ ](\d{2})h[ ](\d{2})m[ ](\d{2})s', start, re.M|re.I)
print ("Start Hours : ", matchObj.group(1))
print ("Start Minutes : ", matchObj.group(2))
print ("Start Seconds : ", matchObj.group(3))


matchObj = re.match( r'(?:Starts|Ends)[ ]in[ ](\d{2})h[ ](\d{2})m[ ](\d{2})s', end, re.M|re.I)
print ("End Hours : ", matchObj.group(1))
print ("End Minutes : ", matchObj.group(2))
print ("End Seconds : ", matchObj.group(3))

输出:

Start Hours :  09                                                                                                                
Start Minutes : 52
Start Seconds : 56
End Hours : 00
End Minutes : 33
End Seconds : 13

通过 regex101 验证:

enter image description here

关于python - 在匹配模式之前匹配单词不定次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52461025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com