I want to extract with regex patterns out of a text like this:
text= """cakes 10 are good.
cakes 10c are good.
cakes 20 21 22 are good.
cakes 30, 31, 32 are good.
cakes 40a, 40b, 40c are good."""
What I want to achieve is to extract the numericals 10, 10c etc., but as a whole.
I build up the pattern as follows:
numerical = r"""
[0-9]{1,4}((\.|\-)?[A-Za-z])? # max 4 digits followed optionally by a letter separated by , or - optionally.
"""
# those could be separated by:
separator = r"""(,\s?)""" # comma followed optionally by space
# code to get the matches with finditer
pattern2 = fr"""(({numerical}
(\s?|({separator})?))+
|
{numerical} # single case
)"""
refs = re.finditer(pattern2, text, re.VERBOSE,)
for element in refs:
print (element.group())
This gives me all the results individually. But I would like to get the ONE match.
Expected result:
10
10c
20 21 22
30, 31, 32
40a, 40b, 40c
Note: I need to use finditer because later on I need to access the spans.
EDIT: It would be very convenient to use this type of pattern composition because then the separator part could be easily and the numerical as well.
With one single regex pattern the code is very difficult to modify by a later reader.