in reply to Add at the begining of text
You almost have it. If you change (\w*) to (.*) your program produces what you want for the test case you have provided. You don't need the /g option on the substitution.