Find same sequence of 2 characters in a sentence

Viewed 65

I have a line that looks like this:

Amount:Category:Date:Description:55544355

My requirement is to find a sequence of two characters, followed later by that same sequence of two characters, followed later by that same sequence of two characters again till all sequences are found. I achieved this as follows:

>>>my_str = 'Amount:Category:Date:Description:55544355'
>>>[item[0] for item in re.findall(r"((..)\2*)", my_str)]
>>>['Am', 'ou', 'nt', ':C', 'at', 'eg', 'or', 'y:', 'Da', 'te', ':D', 'es', 'cr', 'ip', 'ti', 'on', ':5', '55', '44', '35']

This is obviously not the right output since the desired output is:

[[':D',':D'],['55','55'],['at', 'at']]

What am I doing wrong?

2 Answers

Would you please try the following:

my_str = 'Amount:Category:Date:Description:55544355'
print(re.findall(r'(..)(?=.*?\1)', my_str))

Output:

['at', ':D', '55']

If you want to print all occurrences of the characters, another step is required.

You have to use a lookahead with a backreference. To get both values, you can wrap the backreference also in a capture group which will be returned as a tuple by re.findall.

import re
 
print(re.findall(r"(..)(?=.*?(\1))", "Amount:Category:Date:Description:55544355"))

Output

[('at', 'at'), (':D', ':D'), ('55', '55')]

If you want a list of lists:

import re

print([list(elem) for elem in re.findall(r"(..)(?=.*?(\1))", "Amount:Category:Date:Description:55544355")])

Output

[['at', 'at'], [':D', ':D'], ['55', '55']]
Related