Py学习  »  Python

python regex:最多有一个空格的字符串

Oliver Wilken • 6 年前 • 1679 次点击  

你好,我想知道如何创建一个regex模式与一个刺可能包含最多一个空白。更具体地说:

s = "a    b d d  c"
pattern = "(?P<a>.*) +(?P<b>.*) +(?P<c>.*)"
print(re.match(pattern, s).groupdict())

返回:

{'a': 'a    b d d', 'b': '', 'c': 'c'}

我想要:

{'a': 'a', 'b': 'b d d', 'c': 'c'}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/34271
文章 [ 5 ]  |  最新文章 6 年前
Oliver Wilken
Reply   •   1 楼
Oliver Wilken    6 年前

我找到了另一个我更喜欢的解决方案:

import re
s = "a    b dll d  c"
pattern = "(?P<a>(\S*[\t]?)*) +(?P<b>(\S*[\t ]?)*) +(?P<c>(\S*[\t ]?)*)"
print(re.match(pattern, s).groupdict())

这里甚至可以有多个字母。

C.Nivs
Reply   •   2 楼
C.Nivs    6 年前

可能更容易使用 re.split ,因为分隔符是已知的(2个或多个空格),但中间的模式不是。我相信有一个比我更擅长雷杰克斯的人可以解决这个问题,但是通过分开来解决。 \s{2,} ,您可以大大简化问题。

您可以这样编写命名组的字典:

import re
s = "a    b d d  c"

x = dict(zip('abc', re.split('\s{2,}', s)))

x
{'a': 'a', 'b': 'b d d', 'c': 'c'}

第一个arg在哪里 zip 是命名组。要将此扩展到更通用的名称,请执行以下操作:

groups = ['group_1', 'another group', 'third_group']
x = dict(zip(groups, re.split('\s{2,}', s)))

{'group_1': 'a', 'another group': 'b d d', 'third_group': 'c'}
vurmux
Reply   •   3 楼
vurmux    6 年前

看起来您只是想用2个或更多的空格拆分字符串。你可以这样做:

s = "a    b d d  c"
re.split(r' {2,}', s)

将返回您:

['a', 'b d d', 'c']

Oliver Wilken
Reply   •   4 楼
Oliver Wilken    6 年前

在…的帮助下 第四只鸟 回答:我以我想象的方式做到了这一点:

import re
s = "a    b d d  c"
pattern = "(?P<a>\S(?: \S)*) +(?P<b>\S(?: \S)*) +(?P<c>\S(?: \S)*)"
print(re.match(pattern, s).groupdict())
The fourth bird
Reply   •   5 楼
The fourth bird    6 年前

另一种选择是使用zip和dict,并根据匹配的长度生成字符。

您可以使用与非空白字符匹配的重复模式获取最多包含一个空白的匹配项。 \S 在空格后加上非空白字符,重复0+次:

\S(?: \S)*

Regex demo γ Python demo

例如:

import re
a=97
regex = r"\S(?: \S)*"
test_str = "a    b d d  c"
matches = re.findall(regex, test_str)
chars = list(map(chr, range(a, a+len(matches))))
print(dict(zip(chars, matches)))

结果

{'a': 'a', 'b': 'b d d', 'c': 'c'}