Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用正则表达式可以吗_Python_Regex - Fatal编程技术网

Python 使用正则表达式可以吗

Python 使用正则表达式可以吗,python,regex,Python,Regex,我正在使用Python2.7,我非常熟悉正则表达式的使用以及如何在Python中使用它们。我想使用正则表达式将逗号分隔符替换为分号。问题在于,用双QOUTE包装的数据应该保留嵌入的逗号。以下是一个例子: 之前: "3,14","1,000,000",hippo,"cat,dog,frog",plain text,"2,25" 之后: "3,14";"1,000,000";hippo;"cat,dog,frog";plain text;"2,25" 有一个正则表达式可以做到这一点吗?您可以使用

我正在使用Python2.7,我非常熟悉正则表达式的使用以及如何在Python中使用它们。我想使用正则表达式将逗号分隔符替换为分号。问题在于,用双QOUTE包装的数据应该保留嵌入的逗号。以下是一个例子:

之前:

"3,14","1,000,000",hippo,"cat,dog,frog",plain text,"2,25"
之后:

"3,14";"1,000,000";hippo;"cat,dog,frog";plain text;"2,25"

有一个正则表达式可以做到这一点吗?

您可以使用正则表达式拆分,然后加入它:

>>> ';'.join([i.strip(',') for i in re.split(r'(,?"[^"]*",?)?',s) if i])
'"3,14";"1,000,000";hippo;"cat,dog,frog";plain text;"2,25"'
这将产生以下输出:

Before: "3,14","1,000,000",hippo,"cat,dog,frog",plain text,"2,25"
After:  "3,14";"1,000,000";hippo;"cat,dog,frog";plain text;"2,25"
如果需要更多定制,您可以对此进行修补。

您可以使用:

>>> s = 'foo bar,"3,14","1,000,000",hippo,"cat,dog,frog",plain text,"2,25"'
>>> print re.sub(r'(?=(([^"]*"){2})*[^"]*$),', ';', s)
foo bar;"3,14";"1,000,000";hippo;"cat,dog,frog";plain text;"2,25"

只有当逗号在引号之外时,它才会匹配,方法是在
之后匹配偶数个引号,

这个正则表达式似乎可以完成这项工作

,(?=(?:[^"]*"[^"]*")*[^"]*\Z)
改编自:


并使用

进行测试这是另一种方法,可以避免在每次出现时都进行前瞻性测试,直到结束。这是一种(或多或少)针对re模块的
\G
功能仿真。 该模式不测试逗号后面的内容,而是在逗号之前找到项目(显然是逗号),并以一种使每个完整匹配与之前匹配的方式写入

re.sub(r'(?:(?<=,)|^)(?=("(?:"")*(?:[^"]+(?:"")*)*"|[^",]*))\1,', r'\1;', s)

re.sub(r'(?)(?您正在读取csv吗?可能的副本不是直接副本,但假设您要更改csv的分隔符,这是您要查看的问题。您可以使用Python的
csv
包和字符串。这将为您解决引号中的逗号问题。不是同一个问题,因为我要求的是正则表达式解决方案I就像repl.it网站!我如何获得匹配计数?我尝试使用findall和FindItem,但它们返回的计数比实际值少1。findall不返回最后一个匹配?@panofish:正常,只有逗号前的项目匹配,所以最后一个项目无法匹配!@panofish:抱歉,我忘记了引用项目的情况带有转义引号的gins
“abc”def
。已更正。
re.sub(r'(?:(?<=,)|^)(?=("(?:"")*(?:[^"]+(?:"")*)*"|[^",]*))\1,', r'\1;', s)
(?:          # ensures that results are contiguous 
    (?<=,)        # preceded by a comma (so, the one of the last result)
  |             # OR
    ^             # at the start of the string
)
(?= # (?=(a+))\1 is a way to emulate an atomic group: (?>a+)
    (                        # capture the precedent item in group 1
        "(?:"")*(?:[^"]+(?:"")*)*"  # an item between quotes
      |
        [^",]*               # an item without quotes
    )
) \1  # back-reference for the capture group 1
,