是否可以从结果中打印出某个重新匹配对象?
Python
sentence = '''
Tue, 20 August 2019
17:30 - 21:00 CEST
'''
pattern = re.compile(r'\d\d[:]\d\d')
matches = pattern.finditer(sentence)
for match in matches:
print(match)
print(match.group(0))
输出-> print(match)
<re.Match object; span=(20, 25), match='17:30'>
<re.Match object; span=(28, 33), match='21:00'>
输出-> print(match.group(0))
17:30
21:00
是否只能print
进行某些匹配?
print(first re.Match object in list) = 17:30
print(second re.Match object in list) = 21:00
尝试->我为解决此问题而做的尝试
for match in matches:
print(matches[0].group(0))
print(match.group(0))
print(match[0])
print(match)
print(match.__getitem__(0))
print(match.group(0))
print(match.groupdict(0))
print(match.start(0))
print(match.groups)
print(match.group(1))
print(re.match(r'<img.*?>', matches))
print(re.match(r'<img.*?>', match).group(0))
答案 0 :(得分:2)
for match in matches
==您为所有匹配项进行打印。
执行以下操作:
sentence = '''
Tue, 20 August 2019
17:30 - 21:00 CEST
'''
pattern = re.compile(r'\d\d[:]\d\d')
matches = pattern.findall(sentence) # returns a list
print(matches[0].group(0)) # get first element from the list (0-indexed) and get its first group
答案 1 :(得分:1)
如果需要,可以添加一个计数器,在for循环中增加它,并检查它是否是您需要打印的匹配项。
在线查看Python demo:
import re
sentence = '''
Tue, 20 August 2019
17:30 - 21:00 CEST
'''
pattern = re.compile(r'\d\d:\d\d')
cnt = 0 # Initialize the counter
wanted = [1,2] # Defines the 1-based IDs of the matches you want to display
for match in pattern.finditer(sentence):
cnt += 1 # Increment the counter
if cnt in wanted: # If the ID is in wanted IDs
print(match.group()) # Print it