For regular expressions, you can use the match() function to do what you want, and use groups to get your results. Also, do not assign the word string , as this is a built-in function (even if it is deprecated). For your example, if you know that there is always the same amount of fruit every time, it looks like this:
import re input = "bunch(oranges, bananas, apples)" var1, var2, var3 = re.match('bunch\((\w+), (\w+), (\w+)\)', input).group(1, 2, 3)
Here I used a special \w sequence that matches any alphanumeric character or underscore, as described in the documentation
If you donβt know the number of fruits in advance, you can use two calls of regular expressions, one to get the minimum part of the string where the fruits are listed, get rid of the βbunchβ and parentheses, then finditer to extract the fruit names:
import re input = "bunch(oranges, bananas, apples)" [m.group(0) for m in re.finditer('\w+(, )?', re.match('bunch\(([^)]*)\)', input).group(1))]
acjay source share