You shouldn't be using .findall()
at all - .search()
is what you want. It finds the leftmost match, which is what you want (or returns None
if no match exists).
m = re.search(pattern, text)
result = m.group(0) if m else ""
Whether you want to put that in a function is up to you. It's unusual to want to return an empty string if no match is found, which is why nothing like that is built in. It's impossible to get confused about whether .search()
on its own finds a match (it returns None
if it didn't, or an SRE_Match
object if it did).