Conditional construct not working in Python regex

后端 未结 2 1431
执念已碎
执念已碎 2021-01-29 06:08

I an a newbie in python and I want to use my regex in re.sub. I tried it on regex101 and it works. Somehow when I tried to use it on my python (version 3.6) it does

2条回答
  •  爱一瞬间的悲伤
    2021-01-29 07:04

    I suppose you could do this:

    import re
    
    regex = r'(^\w*?[\t]+)'
    s = 'a      bold, italic,           teletype'
    
    def repl(match):
        s = match.group(0)
        return s.rstrip() + ', '
    
    print(re.sub(regex,repl, s))
    

    out

    a, bold, italic,            teletype
    

    Here we are capturing the beginning of the string through any tabs that may occur after the first word, and passing the match to a callable. The callable removes trailing tabs with rstrip and adds a trailing comma.

    Note: if the first tab occurs after the first word, it's not replaced. i.e. 'a bold, italic, teletype' is left unchanged. Is that what you want?

提交回复
热议问题