0

我有以下代码:

import re

vars='"NAME=Product","TYPE=","VERSION=1.2","VISIBILITY=","SRC=","FOLDER=TRUE","Text=foo, containing, commas"'
list = re.findall(r'\w+=".*?"', vars)

for i in range(1,len(list)):
   print list[i]

输出如下所示:

VISIBILITY=","
SRC=","

但是,我想找到(拆分)所有参数,即使是那些本身包含逗号的参数。输出应如下所示:

"NAME=Product"
"TYPE="
"VERSION=1.2"
"VISIBILITY="
"SRC="
"FOLDER=TRUE"
"Text=foo, containing, commas"

我必须对我的正则表达式进行哪些更改?

4

5 回答 5

4

您的正则表达式似乎只期望=等号右侧的值周围有引号,但您的输入在整个表达式周围都有引号。

调整很容易:

re.findall(r'"\w+=.*?"', vars)

在您的示例输入上运行它会给出:

>>> re.findall(r'"\w+=.*?"', vars)
['"NAME=Product"', '"TYPE="', '"VERSION=1.2"', '"VISIBILITY="', '"SRC="', '"FOLDER=TRUE"', '"Text=foo, containing, commas"']
>>> for match in re.findall(r'"\w+=.*?"', vars):
...     print match
... 
"NAME=Product"
"TYPE="
"VERSION=1.2"
"VISIBILITY="
"SRC="
"FOLDER=TRUE"
"Text=foo, containing, commas"
于 2013-03-19T15:33:28.303 回答
3

我不确定您是否需要正则表达式:

[i for i in  vars.split('"') if i not in ',']

出去:

['NAME=Product',
 'TYPE=',
 'VERSION=1.2',
 'VISIBILITY=',
 'SRC=',
 'FOLDER=TRUE',
 'Text=foo, containing, commas']
于 2013-03-19T15:36:06.290 回答
1

我猜这更接近你真正想要的:

 list = re.findall(r'"(\w+)=(.*?)"', VARS)
于 2013-03-19T15:35:22.783 回答
1

您可以使用 CSV 来执行此操作:

import csv

vars='"NAME=Product","TYPE=","VERSION=1.2","VISIBILITY=","SRC=","FOLDER=TRUE","Text=foo, containing, commas"'
reader=csv.reader(vars,delimiter=",",quotechar='"')

print [''.join(tgt) for tgt in reader if ''.join(tgt)]

印刷:

['NAME=Product', 'TYPE=', 
 'VERSION=1.2', 
 'VISIBILITY=', 
 'SRC=', 
 'FOLDER=TRUE', 
 'Text=foo, containing, commas']
于 2013-03-19T15:45:53.190 回答
0
import re

vari=('"NAME=Product",'
      '"TYPE=","VERSION=1.2",'
      '"VISIBILITY=","SRC=","FOLDER=TRUE",'
      '"Text=foo, containing, commas"')

print '\n'.join(re.findall('"[^"=]+=[^"=]*"', vari))
于 2013-03-19T16:29:50.987 回答