Python:查找变量ch的正则表达式

2024-04-26 10:22:52 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我知道如果我想找出所有连续出现的“a”的长度

在input=“1111aaaaaa11111aaaaaaaa11aaaaaaaaaaaaaa11aaa”中,我可以

[len(s) for s in re.findall(r'a+', input)]


但是,我不知道如何使用char变量来实现这一点。例如

CHAR = 'a'
[len(s) for s in re.findall(r'??????', input)]    # Trying to find occurrences of CHARs..

有办法吗??你知道吗


Tags: oftoinreforinputlenfind
2条回答

以下是适用于任何长度字符串的一般解决方案:

CHAR = 'a'
[len(s) for s in re.findall(r'(?:{})+'.format(re.escape(CHAR)), input)]

或使用itertools(仅单个字符)的替代方法:

import itertools
[sum(1 for _ in g) for k, g in itertools.groupby(input) if k == CHAR]

我想你想要的是:

[len(s) for s in re.findall(r'{}+'.format(CHAR), input)]

当然,如果CHAR是一个特殊的值,比如\,这就不起作用了。如果这是一个问题:

[len(s) for s in re.findall(r'{}+'.format(re.escape(CHAR)), input)]

如果要匹配两个或多个而不是一个或多个,则语法为{2,}。正如the docs所说:

{m,n} Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match aaaab or a thousand 'a' characters followed by a b, but not aaab

当我们使用{}进行字符串格式化时,这有点难看,所以让我们切换到%格式:

[len(s) for s in re.findall(r'%s{2,}' % (re.escape(CHAR),), input)]

…或者只是简单的串联:

[len(s) for s in re.findall(re.escape(CHAR) + r'{2,}', input)]

相关问题 更多 >