regex
+ python
This question was asked on stackoverflow and it appeared that the best way to match the expression will be to use a non-capturing group.
Suppose the text is 'bcacaca'
and you want to match any pattern where you have an optional b
followed by zero or more .a
pattern.
Here is an example. For more details, see this on regex101.
import re
## Define text and pattern
text = 'bcacaca dcaca dbcaca'
pattern = 'b?(?:.a)*'
## Evaluate regex
result = re.findall(pattern, text)
# output
# ['bcacaca', '', '', 'caca', '', '', 'bcaca', '']
## Drop empty strings from result
result = list(filter(None, result))
# output
# ['bcacaca', 'caca', 'bcaca']