Python split the w / multiple delimiter string and found the delimiter used

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

import re

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

returns ['someText', 'someValue~']. In this case, ":" was a delimiter for line splitting.

If the string string ="someText~someValue:", then "~" will be a separator to split the string

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

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

+4
source share
3 answers
string ="someText:someValue~"
print re.split("(:|~)",string,1)

, , . 1 .

+4

re.findall.

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

You can use re.findallto find word separators without using look around :

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

Source: https://habr.com/ru/post/1599230/


All Articles