Reputation: 397
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
Upvotes: 4
Views: 711
Reputation: 174696
You may use re.findall.
>>> string ="someText:someValue~"
>>> re.findall(r'^([^:~]*)([:~])([^:~].*)', string)
[('someText', ':', 'someValue~')]
Upvotes: 2
Reputation: 107287
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)
[':', '~', '#']
Upvotes: 0
Reputation: 67968
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.
Upvotes: 4