我很难将以下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
我使用的正则表达式是:
(?:^|,)([^,]*)
(?:^|,)
与行的开头或,
匹配的非捕获组。([^,]*)
与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,',
',d,e'
]
regex = re.compile('(?:^|,)([^,]*)')
for line in lines:
print(regex.findall(line))
打印:
['Ten Thousand', '10000']
['Ten thousand']
['helloasdf', 'x']
['a', 'b', '', 'c', '']
['', 'd', 'e']