I’m having trouble figuring out why the following regex doesn’t seem to work.
I know that I can form other regular expressions to make this work, but I thought this one should work.
re.search ("(\d*)", "prefix 1234 suffix").groups()
('',)
Interestingly, findall seems to work:
re.findall("(\d*)", "prefix 1234 suffix")
['', '', '', '', '', '', '', '1234', '', '', '', '', '', '', '', '']
I understand why that works, but I’m still confused as to why search doesn’t work? My understanding is that match should force it to match the whole string, but search should find the digits anywhere within the string
Because
.searchruns the search once, and matches in the first place it can. Since\d*can match no characters at all, the first place it can match is at the beginning of the string, capturing no characters — so the first capture group is''. It’s doing exactly what you asked it to.If you had made the regex
(\d+)instead, which has to match at least one digit, then the first place it could match would be at the1and it would capture1234.