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.
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')]
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With