user969113
user969113

Reputation: 2429

Remove pattern from string with gsub

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.

Upvotes: 36

Views: 159836

Answers (4)

elcortegano
elcortegano

Reputation: 2694

Just to point out that there is an approach using functions from the tidyverse, which I find more readable than gsub:

a %>% stringr::str_remove(pattern = ".*_")

Upvotes: 2

Praveen
Praveen

Reputation: 19

as.numeric(gsub(pattern=".*_", replacement = '', a)
[1] 5 7

Upvotes: -2

Madhu Sareen
Madhu Sareen

Reputation: 549

Alternatively, you can also try:

gsub("\\S+_", "", a)

Upvotes: 8

Pop
Pop

Reputation: 12411

The following code works on your example :

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

Upvotes: 59

Related Questions