Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by two conditions - wildcard

I need to split a string by a charcter plus a wildcard character:

text1 = "CompanyA-XYZ-257999_31.12.2000"
text2 = "CompanyB-XYZ-057999_31.12.2000"

I want to split that string at the position [-2] or [-0], so right after XYZ. Since I have two "-", I can not simply split by that character. In fact i would like to have a split in the form [-AnyNumber], where AnyNumber should be a wildcard for an integer.

like image 566
Dominik Scheld Avatar asked Jun 14 '26 18:06

Dominik Scheld


2 Answers

Did you try this using re

import re
>>>re.findall("(.+XYZ)-(.+)",text1)
[('CompanyA-XYZ', '257999_31.12.2000')]

or

>>>re.findall("(.+)-(.+)",text1)
[('CompanyA-XYZ', '257999_31.12.2000')]
like image 89
itzMEonTV Avatar answered Jun 16 '26 06:06

itzMEonTV


You don't need a regex, you can split from the right using str.rsplit setting maxsplit to 1:

text1 = "CompanyA-XYZ-257999_31.12.2000"

print(text1.rsplit("-",1))
['CompanyA-XYZ', '257999_31.12.2000']

text2 = "CompanyB-XYZ-057999_31.12.2000"
print(text2.rsplit("-",1))
['CompanyB-XYZ', '057999_31.12.2000']

If you want them stored in variables just unpack:

comp, dte = text2.rsplit("-",1)
print(comp,dte)
('CompanyB-XYZ', '057999_31.12.2000')
like image 37
Padraic Cunningham Avatar answered Jun 16 '26 06:06

Padraic Cunningham