0

例如,有一个类似 的字符串aaaaaab,其中a重复 n 次(在本例中,n=6)。我怎么能得到数字 n ?

然后,如果我想使用 n 将其替换为 make ato n/2 times like aaab,或 n-2 times aaaab。怎么办?

4

4 回答 4

7
s = 'aaaaabbcdddddddd'
[(m.group(1), len(m.group(2))+1) for m in re.finditer(r'(\w)(\1*)', s)]

返回

[('a', 5), ('b', 2), ('c', 1), ('d', 8)]

要使用它来替换字符组:

re.sub(r'(\w)(\1*)', lambda m: m.group(1)*f(len(m.group(2))+1), s)

和:

f = lambda x: x - 2 # returns 'aaadddddd'
f = lambda x: x / 2 # returns 'aabdddd'
f = lambda x: x + 1 # returns 'aaaaaabbbccddddddddd'
于 2012-12-18T10:07:00.623 回答
0

您不能仅使用正则表达式来做到这一点。但是您可以使用正则表达式来提取a's 的字符串,然后检查其长度。

然后您可以创建一个适当长度的替换字符串并进行替换。

于 2012-12-18T10:05:18.957 回答
0

例如,有一个像 aaaaaab 这样的字符串,其中 a 重复 n 次(在本例中,n=6)。我怎么能得到数字 n ?

如果您知道要检查哪个字符,并且只需要重复次数:

>>> from collections import Counter
>>> Counter(i for i in 'aaaaaabbbbbbc')['a']
6

如果您想知道哪些字符被重复以及重复了多少次:

>>> [{k:v} for k,v in Counter(i for i in 'aaaaaabbbbbbc').iteritems() if v > 1]
[{'a': 6}, {'b': 6}]
于 2012-12-18T10:18:15.427 回答
0

要将出现次数的文字n模式替换为重复n/2次数相同的模式,您可以执行以下操作:

>>> import re
>>> text = 'aaaaaab'
>>> re.sub('aa', 'a', text)
'aaab'

如果模式不是文字匹配,则此方法不起作用,并且无法仅使用正则表达式使其起作用。您可以做的事情是使用re.finditer, 并根据匹配中的信息将它们替换为您想要的。

例如,要替换为n/2您可以执行的操作:

>>> text = 'aaaaaab something else aaaab'
>>> matches = list(re.finditer('a+', text))
>>> displ = 0
>>> for match in matches:
...     num_repeat = match.end() - match.start()  #depending on the pattern
...     text = text[:match.start() - displ] + 'a' * (num_repeat // 2) + text[match.end() - displ:]
...     displ += num_repeat // 2
... 
>>> print text
aaab something else aab

或替换为n-2出现次数:

>>> text = 'aaaaaab something else aaaab'
>>> matches = list(re.finditer('a+', text))
>>> displ = 0
>>> for match in matches:
...     num_repeat = match.end() - match.start()
...     text = text[:match.start() - displ] + 'a' * (num_repeat - 2) + text[match.end() - displ:]
...     displ +=  2
... 
>>> print text
aaaab something else aab
于 2012-12-18T10:08:12.630 回答