1

So I have this list of names:

names <- c("stewart,pat", "peterson,greg")

from which I extract only the lastname,firstname items with the following regular expression:

myregexpr <- "(\\w+),(\\w+)?"
str_view(str_extract_all(names, myregexpr), myregexpr)

This yields a view like:

stewart,pat

peterson,greg

My question: Is there a way for me to write the regular expression such that the result would instead look like:

pat_stewart

greg_peterson

i.e. where the result of is first_last? I believe there is a way to do it as I've seen on other, similar questions. I've tried:

myregexpr <- "(\\w+),(\\w+)?\\2_\\1"

but that returns only `character(0)'. I've attempted many versions - some of which crash R studio. Any ideas?

Community
  • 1
  • 1
jmb277
  • 558
  • 4
  • 19
  • 5
    Like `gsub("(.*),(.*)", "\\2_\\1", names)`? – Rich Scriven Feb 18 '17 at 21:24
  • 1
    It's possible (though more complicated) to avoid regex: `sapply(strsplit(names, ','), function(s){paste(rev(s), collapse = '_')})` – alistaire Feb 18 '17 at 21:29
  • I'm looking for a solution that's like the one [I linked to](http://stackoverflow.com/questions/2023334/how-can-i-reorder-substrings-in-a-string) where the reordered is the result. – jmb277 Feb 18 '17 at 21:37
  • @rich-scriven - using `gsub` worked well - also: your regular expression is slicker than mine: `"(.*),(.*)"` - thanks! – jmb277 Feb 18 '17 at 21:52

0 Answers0