python 2.7 - Split string before regex -


i'm trying insert tab (\t) before regex, in string. before "x days ago", x number between 0-999.

the text have looks this:

great product, fast shipping! 22 days ago anon fast shipping. got free! thanks! 42 days ago anon 

desired output:

great product, fast shipping! \t 22 days ago anon fast shipping. got free! thanks! \t 42 days ago anon 

i still new this, , i'm struggling. i've looked around answers, , found close, none identical.

this have far:

text = 'great product, fast shipping! 22 days ago anon' new_text = re.sub(r"\d+ days ago", "\t \d+", text) print new_text 

output:

great product, fast shipping!    \d+ anon 

again, need (note \t):

great product, fast shipping!    22 days ago anon 

you can use backreferences in replacement string. put parantheses around \d+ days ago make captured group , use \\1 inside replacement refer group's text:

>>> text = 'great product, fast shipping! 22 days ago anon' >>> new_text = re.sub(r"(\d+ days ago)", "\t\\1", text) >>> print new_text great product, fast shipping!    22 days ago anon 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -