Я думаю, что ваш код достаточно элегантен и удобочитаем, но если вы хотите усложнить ситуацию, не существует function
, которые возвращают совпадений и заменяют их одновременно, ноВы можете использовать силу re.sub
, которая принимает в repl
аргумент function
, который принимает совпадение в качестве аргумента и должен возвращать str
замену, он используется для динамической замены (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