简体   繁体   English

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

[英]Regular expression to replace a character on odd repeated occurrences in Python

Can't get a regular expression to replace a character on odd repeated occurrences in Python. 无法获得正则表达式来替换Python中奇数重复出现的字符。

Example: 例:

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

to

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

on even occurrences doesn't replace. 即使发生也不会取代。

for example: 例如:

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

Maybe I'm old fashioned (or my regex skills aren't up to par), but this seems to be a lot easier to read: 也许我是老式的(或者我的正则表达式技能不符合标准),但这似乎更容易阅读:

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)

It seems that I might have been a little confused about what you were actually looking for. 似乎我可能对你实际想要的东西感到有些困惑。 Based on the comments, this becomes even easier: 根据评论,这变得更容易:

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) 

This may be not as good as the regex solution, but works: 这可能不如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]: '``...``````.....``...``....``````````...``'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM