Remove pattern from string with gsub

user969113 picture user969113 · Aug 2, 2012 · Viewed 133.4k times · Source

I am struggling to remove the substring before the underscore in my string. I want to use * (wildcard) as the bit before the underscore can vary:

a <- c("foo_5", "bar_7")

a <- gsub("*_", "", a, perl = TRUE)

The result should look like:

> a
[1] 5 7

I also tried stuff like "^*" or "?" but did not really work.

Answer

Pop picture Pop · Aug 2, 2012

The following code works on your example :

gsub(".*_", "", a)