将基本的csv模式与正则表达式匹配

我很难将以下csv类型的输出与正则表达式匹配。例如,使用:

Ten Thousand,10000
Ten thousand
helloasdf,x

我想也许我可以使用基本的:

# start at either the start-of-line or a comma
(^|,)
# consume up through a comma (though end-of-line will not have that
[^,]*
# go until the next comma or end of line
($|,)

但是,即使我将其包装在一个组中并尝试重复该操作,此操作也不起作用。我在这里做错什么事?链接到这里:https://regex101.com/r/AmzZ8n/1

digohao 回答:将基本的csv模式与正则表达式匹配

我使用的正则表达式是:

(?:^|,)([^,]*)
  1. (?:^|,)与行首或,匹配的非捕获组。
  2. ([^,]*)与0个或多个非逗号字符匹配的捕获组。这样可以留空列。

我添加了一些其他测试用例。有问题的一个可能是最后一个:

',d,e'

在某些情况下,Python 3.7之前的regex引擎中存在一个处理0长度匹配的错误。您可能需要从regex存储库中的https://pypi.org/project/regex/安装PYPI软件包,然后:

import regex as re

代码:

import re

lines = [
    'Ten Thousand,10000','Ten thousand','helloasdf,x','a,b,c,',e'
]

regex = re.compile('(?:^|,]*)')
for line in lines:
    print(regex.findall(line))

打印:

['Ten Thousand','10000']
['Ten thousand']
['helloasdf','x']
['a','b','','c','']
['','d','e']

Run Demo

本文链接:https://www.f2er.com/3135018.html

大家都在问