正则表达式替换Python中奇数重复出现的字符

时间:2012-11-17 18:38:39

标签: python regex replace

无法使用正则表达式替换Python中奇数重复出现的字符。

示例:

char = ``...```.....``...`....`````...`

``...``````.....``...``....``````````...``
偶数事件中的

不会替换。

3 个答案:

答案 0 :(得分:4)

例如:

>>> import re
>>> s = "`...```.....``...`....`````...`"
>>> re.sub(r'((?<!`)(``)*`(?!`))', r'\1\1', s)
'``...``````.....``...``....``````````...``'

答案 1 :(得分:3)

也许我是老式的(或者我的正则表达式技能不符合标准),但这似乎更容易阅读:

import re

def double_odd(regex,string):
    """
    Look for groups that match the regex.  Double every second one.
    """
    count = [0]
    def _double(match):
        count[0] += 1
        return match.group(0) if count[0]%2 == 0 else match.group(0)*2
    return re.sub(regex,_double,string)

s = "`...```.....``...`....`````...`"
print double_odd('`',s)
print double_odd('`+',s)

似乎我可能对你实际想要的东西感到有些困惑。根据评论,这变得更加容易:

def odd_repl(match):
    """
    double a match (all of the matched text) when the length of the 
    matched text is odd
    """
    g = match.group(0)
    return g*2 if len(g)%2 == 1 else g

re.sub(regex,odd_repl,your_string) 

答案 2 :(得分:0)

这可能不如regex解决方案好,但有效:

In [101]: s1=re.findall(r'`{1,}',char)

In [102]: s2=re.findall(r'\.{1,}',char)

In [103]: fill=s1[-1] if len(s1[-1])%2==0 else s1[-1]*2

In [104]: "".join("".join((x if len(x)%2==0 else x*2,y)) for x,y in zip(s1,s2))+fill

Out[104]: '``...``````.....``...``....``````````...``'