Python split a string w/ multiple delimiter and fi

2020-03-24 07:09发布

问题:

How to split string with multiple delimiters and find out which delimiter was used to split the string with a maxsplit of 1.

import re

string ="someText:someValue~"
re.split(":|~",string,1)

returns ['someText', 'someValue~']. In this case ":" was the delimiter to split the string.

If string is string ="someText~someValue:", then "~" will be delimiter to split the string

Is there a way to find out which delimitor was used and store that in a variable.

PS: someText and someValue may contain special chars, that are not used in split. Eg: some-Text, some_Text, some$Text

回答1:

string ="someText:someValue~"
print re.split("(:|~)",string,1)

If you put in group,it will appear in the list returned.You can find it from 1 index of list.



回答2:

You may use re.findall.

>>> string ="someText:someValue~"
>>> re.findall(r'^([^:~]*)([:~])([^:~].*)', string)
[('someText', ':', 'someValue~')]


回答3:

You can use re.findall to find the none words delimiters using look around:

>>> string ="someText:someValue~andthsi#istest@"
>>> re.findall('(?<=\w)(\W)(?=\w)',string)
[':', '~', '#']