a = "[abc]def - aaa" # key = "abc" value = "def - aaa"
a2 = "[_abc def]def - aaa" # key = "_abc def" value = "def - aaa"
b = "[abc]"
c = "abc]" # key = "abc" value = ""
d = "[abc]]def/acd" # key = "abc" value = "def/acd"
f = "abc]]" # key = "abc" value = ""
以上只是这些模式的一些示例。我有成千上万个类似的字符串变量。括号可以是单个"]", "["
或双"]]", "[["
,或者在左侧缺失。
我想要的是获取键值对。关键是括号内的字符串(可能缺少左括号)(例如abc
,abc def
)。该值是括号右边的字符串,例如def - aaa
或def/acd
或空字符串。
如何在Python中定义正则表达式模式?我尝试了一些,但是它们不适用于所有变量。
我尝试了re.search(r"([^[].*?)(?:]|]])([^]].*)", a)
,但不适用于re.search(r"([^[].*?)(?:]|]])([^]].*)", b)
python大神给出的解决方案
如果您只想忽略方括号,则可以使用以下命令:
words = re.split('[\[\]]+', key_value)
words = filter(None, words) # remove empty words
key = words[0]
value = words[1] if len(words) > 1 else None
此模式是从文档中复制的:re — Regular expression operations