In Python, is there a way to search, return matched string, and replace matched strings all at the same time? See example below:
a = "[fox] dog turtle [cat]"
Goal:
result1 = "fox" #(first match inside bracket)
result2 = "cat" #(second match inside bracket)
result3 = "dog turtle" #(remaining string after removing matched text inside brackets
What I have:
result1, result2 = re.findall('\[.*?\]', a)
result3 = re.sub('\[.*?\]', '', a)
It seems redundant and clunky to have to run re
twice. Is there a more elegant way to achieve this?
I think your code is Elegant enough and readable, but if you want to complicate things, There is not function
that return matches
and replace them in the same time but you can use the force of re.sub
that
accepts in repl
argument a function
that accept the matche as argument and
should return a str
replacement, it's used for dynamic replacing (example: when the replacing depends on the value of the match it self).
import re
a = '[fox] dog turtle [cat]'
matches = []
# append method of list return None so the return string is always `''`
# so when ever we find a match to replace we add it to matches list and replace it with `''`
# in your result you return the fox without brackets so i'm using a capture group inside the brackets
text = re.sub('\[(.*?)\]', lambda m: matches.append(m.group(1)) or '', a)
print(matches) # ['fox', 'cat']
print(text) # dog turtle