How to add incrementing values to string for every time string occurs in Stata?

Viewed 119

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'         
        }
1 Answers
* Example generated by -dataex-. To install: ssc install dataex
clear
input str71 talk
"will you please come here please do it as soon as you can if you please"
end

// Install egenmore if not installed already
* ssc install egenmore

clonevar wanted = talk

// count occurrences of "please"
egen countplease = noccur(talk), string(please)

// Loop over 1 to max number of occurrences
sum countplease, meanonly 
forval i = 1/`r(max)' {
    replace wanted = ustrregexrf(wanted, "\bplease\b", "please`i'")
}
list

     +---------------------------------------------------------------------------------------+
  1. |                                                                           talk        |
     |        will you please come here please do it as soon as you can if you please        |
     |---------------------------------------------------------------------------------------|
     |                                                                     wanted | countp~e |
     | will you please1 come here please2 do it as soon as you can if you please3 |        3 |
     +---------------------------------------------------------------------------------------+
Related