Question: I have several string variables that I would like to turn into a comma-separated string in one variable. When I use `egen concat` with the `punct(", ")` option I get trailing commas if that associated row is missing from entries, which is common in my data.

I thought that I could remove the trailing commas with `regexm()` and a for loop, but my concatenated string variable doesn't change.

How do I get this REGEX to match in Stata? (Or maybe I'm on totally the wrong path.)

```
clear
input str5 name1    str5 name2  str5 name3 
Tom     Dick    Harry
Tom     ""      ""
end
ds name*
local n: word count `r(varlist)'
display `n'
egen names = concat(name*), punct(", ")
generate names2 = names
forvalues i = 1/`n' {
    replace names2 = regexr(names2, ",.$", "")
}
list

```

This provides:

```
. list

     +-------------------------------------------------------------+
     | name1   name2   name3              names             names2 |
     |-------------------------------------------------------------|
  1. |   Tom    Dick   Harry   Tom, Dick, Harry   Tom, Dick, Harry |
  2. |   Tom                             Tom, ,             Tom, , |
     +-------------------------------------------------------------+

```

Answer: 
`egen`'s `concat()` function just implements a loop. You can write your own instead: 

```
gen names = name1 

forval j = 2/4 { 
    replace names = cond(mi(names), name`j', names + "," + name`j') if !mi(name`j')
} 

```
Does something like this work for your data?

```
clear

input str5 name1    str5 name2  str5 name3 str5 name4
Tom     Dick    Harry Hank
Tom     ""      ""  Hank
Tom     ""    Harry "" Hank
Tom     ""    "" ""
end  

list

egen names = concat(name*), punct(" ")
gen names2 = subinstr(itrim(names), " ", ", ", .)

list

```

If your string variables have spaces, e.g. "Hank and Gloria", that will fail.