python – How to Split a String from substrings regex patterns with placeholders and keeping the delimiter

Similar questions have been answered, yet I did not find the right one for the following case.

Close related questions:

How do I use regular expressions in Python with placeholder text?

How to replace placeholders in python strings

In Python, how do I split a string and keep the separators?

I need to split this string to get the following output:

txt = "MCMXLIII"

Needed output:

['M', 'CM', 'XL', 'III']

I tested this:

import re

txt = "MCMXLIII"

print(re.sub('(CM)|(XL)', '❤️{0}❤️|❤️{1}❤️', txt).format("CM", "XL").split('❤️'))

Output:

['M', 'CM', '|', 'XL', '', 'CM', '|', 'XL', 'III']

I also tested this:

import re

txt = "MCMXLIII"


print(re.sub('(CM)|(XL)', '(❤️{0}❤️|❤️{1}❤️)', txt).format("CM", "XL").split('❤️'))

Output:

['M(', 'CM', '|', 'XL', ')(', 'CM', '|', 'XL', ')III']

Finally I tested this:


import re

txt = "MCMXLIII"

print(re.sub('(XL)', '❤️{0}❤️', (re.sub('(CM)', '❤️{0}❤️', txt).format("CM"))).format("XL").split('❤️'))

Output:
['M', 'CM', '', 'XL', 'III']

If that’s of help here’s the correct output in Google Sheets formula version:

=SPLIT(
IF(
REGEXMATCH(A1,"(CM)|(XL)"),REGEXREPLACE(A1, "(CM)|(XL)","❤️$0❤️")),"❤️")

Google Sheets output:

splitplaceholders

Read more here: Source link