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
Solution 1:
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')]
Solution 2:
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')
Solution 3:
>>>text1 = "CompanyA-XYZ-257999_31.12.2000">>>text1[:-18]
'CompanyA-XYZ'
>>>text1[-17:]
'257999_31.12.2000'
Solution 4:
split by [-AnyNumber]
In[5]: importreIn[6]: re.split('-(?:[0-9])', text1)
Out[6]: ['CompanyA-XYZ', '57999_31.12.2000']In[7]: re.split('-(?:[0-9])', text2)
Out[7]: ['CompanyB-XYZ', '57999_31.12.2000']
Solution 5:
Using regex with a lookahead assertion:
>>>import re>>>text1 = "CompanyA-XYZ-257999_31.12.2000">>>text2 = "CompanyB-XYZ-057999_31.12.2000">>>re.split('-(?=\d)', text1)
['CompanyA-XYZ', '257999_31.12.2000']
>>>re.split('-(?=\d)', text2)
['CompanyB-XYZ', '057999_31.12.2000']
Post a Comment for "Split String By Two Conditions - Wildcard"