Tôi không biết điều này sẽ làm sáng tỏ mọi thứ nhiều hơn, nhưng hãy thử tưởng tượng những gì xảy ra dưới mui xe một cách đơn giản, chúng ta sẽ tổng hợp những gì xảy ra bằng cách sử dụng khớp
# group(0) return the matched string the captured groups are returned in groups or you can access them
# using group(1), group(2)....... in your case there is only one group, one group will capture only
# one part so when you do this
string = 'abcdla'
print(re.match('(ab|cd)', string).group(0)) # only 'ab' is matched and the group will capture 'ab'
print(re.match('(ab|cd)+', string).group(0)) # this will match 'abcd' the group will capture only this part 'cd' the last iteration
findall
khớp và tiêu thụ chuỗi cùng một lúc, hãy tưởng tượng điều gì xảy ra với REGEX này '(ab|cd)'
:
'abcdabla' ---> 1: match: 'ab' | capture : ab | left to process: 'cdabla'
'cdabla' ---> 2: match: 'cd' | capture : cd | left to process: 'abla'
'abla' ---> 3: match: 'ab' | capture : ab | left to process: 'la'
'la' ---> 4: match: '' | capture : None | left to process: ''
--- final : result captured ['ab', 'cd', 'ab']
Bây giờ điều tương tự với '(ab|cd)+'
'abcdabla' ---> 1: match: 'abcdab' | capture : 'ab' | left to process: 'la'
'la' ---> 2: match: '' | capture : None | left to process: ''
---> final result : ['ab']
Tôi hy vọng điều này sẽ làm rõ một chút.