Quoted regular expression, equal sign, and dot for an attribute / value pair

I need help analyzing user input in python using a mixture of regex and repeating the result from regex. An example input looks like this:

KeylessBuy=f and not (Feedback.color = green or comment.color=green) 
and not "BIN State".color = white and comment="got it right"

The result of the separation should be:

KeylessBuy=f
Feedback.color = green
comment.color=green
"BIN State".color = white
comment="got it right"

So, we select only those parts that directly surround the "=" sign. I tried (including):

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

This only "almost" gives the correct answer. Any help is much appreciated! Thank you so much. Mark

+4
source share
4 answers

You can use the following:

>>> 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"
+3
source

I got it according to what you are looking for using

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

regex

+1

. 1.

((\"[^=]*|[\w\.]+)\s*=\s*(\w+|\"[^"]*\"))

DEMO

:

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"

DEMO

0

All Articles