the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > finditer method returns an iteration of the object, the object contains all the matching results of iterators. Each Match result is a match object. You can use this object to obtain detailed information about the match result, including the contents in parentheses in the regular expression.
If you find that the Match object returned by finditer does not contain results in parentheses, chances are that your regular expression did not use parentheses properly. Make sure you use parentheses to group properly in the regular expression, and use the group() or group(index) method of the Match object to get the match inside the parentheses.
import re pattern = r'(\d+)-(\d+)' text = '2010-2020' # 使用finditer方法 for match in re.finditer(pattern, text): # 获取括号内的结果 print(match.group(1), match.group(2)) # 使用findall方法 matches = re.findall(pattern, text) for match in matches: # 获取括号内的结果 print(match, match)
In the above example, we used a regular expression containing parentheses to match the range of numbers in the text string. Use the finditer method to iterate over each match and the group method to get the results in parentheses. Use the findall method to get all the matches and access the results in parentheses through the index.