Split a string with multiple delimiters from an array (Python)

Given an array of delimiters:

columns = ["Name:", "ID:", "Date:", "Building:", "Room:", "Notes:"]

and a line in which some columns are left empty (and there is a random empty space):

input = "Name:      JohnID:123:45Date:  8/2/17Building:Room:Notes:  i love notes"

How can I get this:

["John", "123:45", "8/2/17", "", "", "i love notes"]

I tried just removing the substrings to see where I can go from there, but I was still stuck

import re
input = re.sub(r'|'.join(map(re.escape, columns)), "", input)
+4
source share
2 answers

use a list to generate a regular expression by pasting (.*)between them, then use stripto remove spaces:

import re

columns = ["Name:", "ID:", "Date:", "Building:", "Room:", "Notes:"]
s = "Name:      JohnID:123:45Date:  8/2/17Building:Room:Notes:  i love notes"

result = [x.strip() for x in re.match("".join(map("{}(.*)".format,columns)),s).groups()]

print(result)

gives:

['John', '123:45', '8/2/17', '', '', 'i love notes']

the part stripcan be processed by a regular expression due to a more complex regular expression, but a simpler general expression:

result = re.match("".join(map("{}\s*(.*)\s*".format,columns)),s).groups()

: , ( ):

result = re.match("".join(["{}\s*(.*)\s*".format(re.escape(x)) for x in columns]),s).groups()
+5

re.split?

>>> import re
>>> columns = ["Name:", "ID:", "Date:", "Building:", "Room:", "Notes:"]
>>> i = "Name:      JohnID:123:45Date:  8/2/17Building:Room:Notes:  i love notes"
>>> re.split('|'.join(map(re.escape, columns)), i)
['', '      John', '123:45', '  8/2/17', '', '', '  i love notes']

, :

>>> re.split(r'\s*' + (r'\s*|\s*'.join(map(re.escape, columns))) + r'\s*', i.strip())
['', 'John', '123:45', '8/2/17', '', '', '  i love notes']
+3

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


All Articles