Python 逗号分隔词正则表达式

Python 逗号分隔词正则表达式,python,regex,Python,Regex,我在尝试解析表达式时遇到一些问题,例如: word1, word2[a,b,c], word3, ..., wordN word1,word2,word3 word1[a,b,c],word2,word3 word1[a,b,c],word2[e,f,g],word3 word1[a,b,c],word2[e,f,g],word3[i,j,l] 我想参加以下小组: g1: word1 g2: word2[a,b,c] g3: word3 请注意,[.+]是可选的,正则表达式必须能够匹配

我在尝试解析表达式时遇到一些问题,例如:

word1, word2[a,b,c],   word3, ..., wordN
word1,word2,word3
word1[a,b,c],word2,word3
word1[a,b,c],word2[e,f,g],word3
word1[a,b,c],word2[e,f,g],word3[i,j,l]
我想参加以下小组:

g1: word1
g2: word2[a,b,c]
g3: word3
请注意,[.+]是可选的,正则表达式必须能够匹配以下表达式:

word1, word2[a,b,c],   word3, ..., wordN
word1,word2,word3
word1[a,b,c],word2,word3
word1[a,b,c],word2[e,f,g],word3
word1[a,b,c],word2[e,f,g],word3[i,j,l]
我做了一些尝试,但找不到正确分隔组的方法。

我尝试了这个正则表达式,并将您的表达式粘贴到“测试字符串”框中

每个单词用逗号分隔,其形式如下:

([a-zA-Z0-9]+(?:\[.*\])?)
说明:

(
  [a-zA-Z0-9]+ # one or more alphanumeric characters (could use \w)
  (?:\[.*\])? # an optional sequence surrounded by []s. (?: ) means a non-capturing group
)

就目前而言,这似乎是可行的:

import re
rgx = re.compile("(\w+(\[.*?\])*).*?,?")
[key for key, val in rgx.findall("word1, word2[a,b,[c,,,]],     word,3")]

# this regex starts by looking for alpha numberic characters with \w+
# then within that it looks if a `[` is present then till we encounter end of bracket ']' consider everything (\[.*?\])*.
# the output of this is a tuple as ('word2[a,b,c]', '[a,b,c]')
# we iterate over the tuple and take only the 1st values in the tuple
输出:

['word1', 'word2[a,b,[c,,,]', 'word', '3']
['word1[bbbb,cccc]', 'word2[bbbb,cccc]']
另一个例子

[key for key, val in rgx.findall("word1[bbbb,cccc],word2[bbbb,cccc] ")]
输出:

['word1', 'word2[a,b,[c,,,]', 'word', '3']
['word1[bbbb,cccc]', 'word2[bbbb,cccc]']

PS:仍在重新调整以改进它。

您可以使用
re.split
仅对括号外的逗号进行拆分。这可以通过这样一个事实来确定,即这些逗号永远不会在开始括号之前匹配结束括号(使用负向前看)。只有在非嵌套方括号中才能使用此技巧

import re
print(re.split(r',(?![^[]*\])', 'word1[a,b,c],word2[e,f,g],word3'))
输出
['word1[a,b,c],'word2[e,f,g],'word3']


您可能想考虑使用某种解析器进行此操作。逗号可以嵌套,正则表达式不能很好地处理嵌套结构。谢谢。我尝试只使用std python的东西,所以我不想依赖第三方解析器:(这些括号可以嵌套吗?否则好的旧
,(?![^[]*\])
应该可以工作。非常感谢。我正在使用以下表达式测试它,但它似乎不工作:word1[bbbb,cccc],word2[bbbb,cccc]哦,我看到你的帖子说这是N个单词的-我以为正好是3个单词。是的,我的错。我只是添加了这个以避免混淆。无论如何谢谢你的回复。谢谢先生。你的解决方案似乎工作正常。请你提供一些关于它的解释,特别是正则表达式本身。我看不出“,”是否包含/处理分隔部分?@redobot添加了解释。如果需要更多说明,请告诉我。非常感谢。您的解决方案很好,只是要补充一点,它不会强制分隔符为逗号(对我来说没问题),我用其他分隔符测试了代码(:例如)而且它也可以工作。我会接受它作为解决方案,即使在答案中强调这一点是很好的。再次感谢:)@redobot问题可能会发生,如果你的单词不完全由单词字符组成,或者如果括号可以嵌套(你还没有回答我关于这个问题的评论)对此表示抱歉。括号不能嵌套。而且单词只能有字母数字字符。