Split string before regex

Isak

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
halex

You can use backreferences in your replacement string. Put parantheses around the \d+ days ago to make it a captured group and use \\1 inside your replacement to refer to this 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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related