2

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

例子:

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

``...``````.....``...``....``````````...``

即使发生也不会取代。

4

3 回答 3

4

例如:

>>> import re
>>> s = "`...```.....``...`....`````...`"
>>> re.sub(r'((?<!`)(``)*`(?!`))', r'\1\1', s)
'``...``````.....``...``....``````````...``'
于 2012-11-17T18:44:48.653 回答
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) 
于 2012-11-17T18:59:04.920 回答
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]: '``...``````.....``...``....``````````...``'
于 2012-11-17T19:10:26.743 回答