Split string by two conditions - wildcard

痴心易碎 提交于 2021-01-27 16:47:09

问题


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.


回答1:


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')



回答2:


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



回答3:


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

>>> text1[:-18]
'CompanyA-XYZ'

>>> text1[-17:]
'257999_31.12.2000'



回答4:


split by [-AnyNumber]

In [5]: import re

In [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']



回答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']


来源:https://stackoverflow.com/questions/29536683/split-string-by-two-conditions-wildcard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!