Tanwir Khan
Tanwir Khan

Reputation: 33

Splitting a string into multiple string using re.split()

I have a string that I am trying to split into 2 strings using Regex to form a list. Below is the string:

Input: 'TLSD_IBPDEq.'

Output: ['', '']

Expected Output: ['TLSD_IBPD', 'Eq.']

Below is what I have tried but is not working

pattern = r"\S*Eq[\.,]"
l = re.split(pattern,"TLSD_IBPDEq.")

print(l)  => ['', '']

Upvotes: 2

Views: 48

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195653

You can do it without re:

s = "TLSD_IBPDEq."

if s.endswith(("Eq.", "Eq,")):
    print([s[:-3], s[-3:]])

Prints:

['TLSD_IBPD', 'Eq.']

Solution with re:

import re

s = "TLSD_IBPDEq."

print(list(re.search(r"(\S*)(Eq[.,])$", s).groups()))

Prints:

['TLSD_IBPD', 'Eq.']

Upvotes: 1

Michael M.
Michael M.

Reputation: 11100

If I understand, then you can apply the answer from this question. If you need to use a regex to solve this, then use a capture group and remove the last (empty) element, like this:

pattern = r"(Eq\.)$"
l = re.split(pattern, "TLSD_IBPDEq.")[:-1]
print(l)  # => ['TLSD_IBPD', 'Eq.']

Upvotes: 1

Related Questions