regular expression not finding all the patterns in a string

Question:

I am using Python regex to find a pattern with pipes "|" enclosing any number of asterics. for example, my program should return
| ** | or | * | or | *** | etc.

I created this regular expression below. But it seems to miss few of the patterns in the substring.

import re
pat = r"|*+|"
string = "*|**|*|***|**"
print(re.findall(pat,string))

I am getting this output ❌❌

["|**|" , "|***|"]

instead I want this as output ✅

[ "|**|" , "|*|" , "|***|" ]
Asked By: hassan

||

Answers:

You could solve this by my comment above or import the regex module which allows an argument to findall that permits overlapping matches. (You would need to install this module with pip as it is not part of the standard distribution).

import regex
pat = r"|*+|"
string = "*|**|*|***|**"

print(regex.findall(pat,string, overlapped=True))

Prints

['|**|', '|*|', '|***|']
Answered By: Chris Charley