相关疑难解决方法(0)

python regex:捕获包含空格的多个字符串的部分

我试图从类似于的字符串中捕获子字符串

'some string, another string, '
Run Code Online (Sandbox Code Playgroud)

我想要结果匹配组

('some string', 'another string')
Run Code Online (Sandbox Code Playgroud)

我目前的解决方案

>>> from re import match
>>> match(2 * '(.*?), ', 'some string, another string, ').groups()
('some string', 'another string')
Run Code Online (Sandbox Code Playgroud)

虽然工作,但不切实际 - 我在这里展示的当然是复杂程度与我在实际项目中所做的相比大大减少了; 我想只使用一个'直的'(非计算)正则表达式模式.不幸的是,到目前为止我的尝试失败了:

这不匹配(结果为None),因为{2}仅应用于空间,而不是整个字符串:

>>> match('.*?, {2}', 'some string, another string, ')
Run Code Online (Sandbox Code Playgroud)

在重复的字符串周围添加括号在结果中有逗号和空格

>>> match('(.*?, ){2}', 'some string, another string, ').groups()
('another string, ',)
Run Code Online (Sandbox Code Playgroud)

添加另一组parantheses确实解决了这个问题,但是让我太过分了:

>>> match('((.*?), ){2}', 'some string, another string, ').groups()
('another string, ', 'another string')
Run Code Online (Sandbox Code Playgroud)

添加非捕获修饰符可以改善结果,但仍会错过第一个字符串

>>> match('(?:(.*?), ){2}', 'some string, another string, ').groups()
('another …
Run Code Online (Sandbox Code Playgroud)

python regex space repeat

0
推荐指数
1
解决办法
2818
查看次数

标签 统计

python ×1

regex ×1

repeat ×1

space ×1