我需要帮助解析python中的用户输入,使用正则表达式的混合并迭代正则表达式的结果。示例输入如下所示:
KeylessBuy=f and not (Feedback.color = green or comment.color=green)
and not "BIN State".color = white and comment="got it right"
拆分结果应为:
KeylessBuy=f
Feedback.color = green
comment.color=green
"BIN State".color = white
comment="got it right"
因此只选择那些直接围绕" =" -sign的部分。我试过(等等):
r'(\w+\s{0,}(?<!=)={1,2}(?!=)\s{0,}\w+)'
r'|("(.*?)"\s{0,}(?<!=)={1,2}(?!=)\s{0,}\w+)'
r'|("(.*?)"\s{0,}(?<!=)={1,2}(?!=)\s{0,}"(.*?)")'
r'|(\w+\s{0,}(?<!=)={1,2}(?!=)\s{0,}"(.*?)")'
r'|(\w+\s{0,}\.\w+\s{0,}(?<!=)={1,2}(?!=)\s{0,}"(.*?)")',
这只是&#34;几乎&#34;给出了正确的答案。 任何帮助都非常感谢!非常感谢。标记
答案 0 :(得分:3)
您可以使用以下内容:
>>> import re
>>> s = '''KeylessBuy=f and not (Feedback.color = green or comment.color=green)
and not "BIN State".color = white and comment="got it right"'''
>>> m = re.findall(r'(?:[\w.]+|"[^=]*)\s*=\s*(?:\w+|"[^"]*")', s)
>>> for x in m:
... print x
KeylessBuy=f
Feedback.color = green
comment.color=green
"BIN State".color = white
comment="got it right"
答案 1 :(得分:1)
答案 2 :(得分:0)
这应该有效。从索引1获取匹配的组。
((\"[^=]*|[\w\.]+)\s*=\s*(\w+|\"[^"]*\"))
示例代码:
import re
p = re.compile(ur'((\"[^=]*|[\w\.]+)\s*=\s*(\w+|\"[^"]*\"))')
test_str = u"KeylessBuy=f and not (Feedback.color = green or comment.color=green) \nand not \"BIN State\".color = white and comment=\"got it right\""
re.findall(p, test_str)
答案 3 :(得分:0)
你可以试试下面的正则表达式,
>>> str = '''
... KeylessBuy=f and not (Feedback.color = green or comment.color=green)
... and not "BIN State".color = white and comment="got it right"'''
>>> m = re.findall(r'(?:\"[\w ]+\")?[\w.]+\s*=\s*(?:\w+)?(?:\"[\w ]+\")?', str)
>>> m
['KeylessBuy=f', 'Feedback.color = green', 'comment.color=green', '"BIN State".color = white', 'comment="got it right"']
>>> for item in m:
... print item
...
KeylessBuy=f
Feedback.color = green
comment.color=green
"BIN State".color = white
comment="got it right"