I have a string variable named talk. Let's say I want to find all instances of the word "please" in talk and, within each row, add a suffix to each "please" that contains an incrementing count of the word.
For example, if talk looks like this:
"will you please come here please do it as soon as you can if you please"
I want it to look like this instead:
"will you please1 come here please2 do it as soon as you can if you please3"
In other words, "please1" indicates that it's the first "please" to occur, "please2" is the second, etc.
I have written some code (below) using regex and several loops but it doesn't work perfectly and, even I could work out the kinks, it seems overly complicated. Is there a simpler way to do this?
# I first extract the portion of 'talk' beginning from the 1st please to the last
gen talk_pl = strtrim(stritrim(regexs(0))) if regexm(talk, "please.+please")
# I count the number of times "please" occurs in 'talk_pl'
egen count = noccur(talk_pl), string("please")
# in the loop below, x = 2nd to last word; i = 3rd to last word
qui levelsof count
foreach n in `r(levels)' {
local i = `n' -1
local x = `i' -1
replace talk_pl = regexrf(talk_pl, "please$", "please`n'") if count == `n'
replace talk_pl = regexrf(talk_pl, "please (?=.+?please`n')", "please`i' ") if count == `n'
replace talk_pl = regexrf(talk_pl, "please (?=.+?please`i')", "please`x' ") if count == `n'
}