带引号、等号和点的正则表达式用于属性/值对。

4

我需要帮助使用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"

所以只选择直接围绕“=”符号的部分。我尝试了以下方法(包括其他方法):

    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,}"(.*?)")',

这只是“几乎”给出了正确答案。非常感谢帮助!谢谢。马克

4个回答

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
我用以下代码使其符合您的要求:

“我用以下代码使其符合您的要求:”

((?:"[^"]+")?[\w\.]+?) ?= ?((?:"[^"]+")|\w+)

你可以在这里查看正则表达式演示。

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)

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"

演示


@RevanProdigalKnight 现在已经更新。抱歉,网络连接慢...:( - Avinash Raj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接