Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python re.split how to split on multiple patterns specified from variables

I am trying to split a string on multiple sub strings, but I can not get re.split() to accept 2 variables as the patterns. I see multiple example of how to use individual characters or combinations of special characters as patterns, but nothing about using variables.

These are dummy inputs. The strings will be more complicated, change based on other factors, and may occur multiple times.

string_to_split = "This_is_the_string_to_split"
pattern1 = "_is_"
pattern2 = "_to_"

Desired Resut:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# ['This', 'the_string', 'split']

I can split specifying either pattern alone, or the values of the patterns when specified as a regex

re.split(pattern1, string_to_split)
# ['This', 'the_string_to_split']
re.split(pattern2, string_to_split)
# ['This_is_the_string', 'split']
re.split(r'_is_|_to_', string_to_split)
# ['This', 'the_string', 'split']

I can not use the variable names (pattern1, pattern2) to both be used simultaneously

re.split(pattern1|pattern2, string_to_split)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: unsupported operand type(s) for |: 'str' and 'str'
re.split(r'pattern1|pattern2', string_to_split)
['This_is_the_string_to_split']

>Solution :

Combine the patterns and the ‘|’ operator using string concatenation:

re.split(pattern1 + "|" + pattern2, string_to_split)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading