给定一系列分隔符:
columns = ["Name:", "ID:", "Date:", "Building:", "Room:", "Notes:"]
和一些字符串,其中一些列留空(并且有随机空格):
input = "Name: JohnID:123:45Date: 8/2/17Building:Room:Notes: i love notes"
我怎样才能得到这个:
["John", "123:45", "8/2/17", "", "", "i love notes"]
我试过简单地删除子串,看看我可以从哪里去,但我还是卡住了
import re
input = re.sub(r'|'.join(map(re.escape, columns)), "", input)
答案 0 :(得分:5)
使用列表生成正则表达式,在其间插入(.*)
,然后使用strip
删除空格:
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)
的产率:
['John', '123:45', '8/2/17', '', '', 'i love notes']
strip
部分可以由正则表达式处理,代价是更复杂的正则表达式,但整体表达式更简单:
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()
答案 1 :(得分:3)
如何使用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']