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
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?