samedi 25 avril 2015

Split string before regex


I'm trying to insert a tab (\t) before a regex, in a string. Before "x days ago", where x is a number between 0-999.

The text I have looks like this:

Great product, fast shipping! 22 days ago anon
Fast shipping. Got an extra free! Thanks! 42 days ago anon

Desired output:

Great product, fast shipping! \t 22 days ago anon
Fast shipping. Got an extra free! Thanks! \t 42 days ago anon

I am still new to this, and I'm struggling. I've looked around for answers, and found some that are close, but none that are identical.

This is what I have so 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, what I need is (note the \t):

Great product, fast shipping!    22 days ago anon

Note: I am open for all answers, it doesn't have to involve splitting!


Aucun commentaire:

Enregistrer un commentaire