Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按多个分隔符拆分字符串,忽略重复分隔符_Python_Regex - Fatal编程技术网

Python 按多个分隔符拆分字符串,忽略重复分隔符

Python 按多个分隔符拆分字符串,忽略重复分隔符,python,regex,Python,Regex,我试图分析一个字符串,该字符串包含多个可能重复的分隔符 输入字符串: -abc,-def,ghi jkl,mno 预期回报: [“abc”、“def”、“ghi”、“jkl”、“mno”] 我试过了 re.split(",|-", string) 但回报是: ['', 'abc', '', 'def', 'ghi', 'jkl', 'mno'] 使用re.findall: re.findall(r'[^-,]+', string) 看 Python代码: import

我试图分析一个字符串,该字符串包含多个可能重复的分隔符

输入字符串: -abc,-def,ghi jkl,mno

预期回报: [“abc”、“def”、“ghi”、“jkl”、“mno”]

我试过了

re.split(",|-", string)
但回报是:

['', 'abc', '', 'def', 'ghi', 'jkl', 'mno']

使用
re.findall

re.findall(r'[^-,]+', string)

Python代码:

import re
regex = r"[^,-]+"
string = "-abc,-def,ghi-jkl,mno"
print(re.findall(regex, string))

结果:
['abc'、'def'、'ghi'、'jkl'、'mno']
使用
re.findall

re.findall(r'[^-,]+', string)

Python代码:

import re
regex = r"[^,-]+"
string = "-abc,-def,ghi-jkl,mno"
print(re.findall(regex, string))

结果:
['abc'、'def'、'ghi'、'jkl'、'mno']

您可以像这样过滤结果

>>> list(filter(len, re.split(r"[,|-]+", s)))
['abc', 'def', 'ghi', 'jkl', 'mno']

您可以像这样过滤结果

>>> list(filter(len, re.split(r"[,|-]+", s)))
['abc', 'def', 'ghi', 'jkl', 'mno']

我想你想用量词
[,-]+
或匹配来代替拆分。这是否回答了你的问题?不,它不能回答这个问题。我想你想用量词
[,-]+
或匹配来代替拆分。这能回答你的问题吗?不,它没有回答这个问题。