Home > Mobile >  Splitting a string into multiple string using re.split()
Splitting a string into multiple string using re.split()

Time:11-23

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)  => ['', '']

CodePudding user response:

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.']

CodePudding user response:

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.']

CodePudding user response:

You should use the following pattern to match Eq.

pattern = r'Eq\.'
  • Related