在空格上拆分字符串,同时忽略特定的空格

时间:2016-10-16 13:51:33

标签: python regex split

我想在所有空格上拆分一个字符串,除了前面有逗号的空格。

示例:

"abc de45+ Pas hfa, underak (333)"

将拆分为:

Item 1: abc
Item 2: de45+
Item 3: Pas
Item 4: hfa, underak
Item 5: (333)

2 个答案:

答案 0 :(得分:2)

你应该按(?<!,)\s分割 点击此处:https://regex101.com/r/9VXO49/1

答案 1 :(得分:0)

如果您只想在空格处拆分,只需使用split()

即可
a = "abc de45+ Pas hfa, underak (333)"
split_str = a.split(' ')    #Splits only at space

如果你想按空格分割而不是像@Beloo所建议的那样,请使用正则表达式

import re

a = "abc de45+ Pas hfa, underak (333)"
split_str = re.split(' ' , a)    #Splits just at spaces
split_str = re.split('[ .:]', a)    #Splits at spaces, periods, and colons
split_str = re.split('(?<!,)[ ]' , a)    #Splits at spaces, excluding commas

正如您可能猜到的那样,如果您想要排除某个字符,只需将其置于(?<!)之间