Home > Net >  Remove part of string after 3-digit number
Remove part of string after 3-digit number

Time:06-07

I would like to substitute the strings in the list by cutting each string after the first 3-digit number.

a <- c("MTH314PHY410","LB471LB472","PHY472CHM141")

I would like for it to look something like

a <- c("MTH314","LB471","PHY472")

I have tried something like

b <- gsub("[100-999].*","",a)

but it returns c("MTH","LB","PHY") without the first number

CodePudding user response:

A possible solution, based on stringr::str_remove:

library(stringr)

a <- c("MTH314PHY410","LB471LB472","PHY472CHM141")

str_remove(a, "(?<=\\d{3}).*")

#> [1] "MTH314" "LB471"  "PHY472"

CodePudding user response:

c("MTH314PHY410","LB471LB472","PHY472CHM141") %>% 
    stringr::str_extract('. ?\\d{3}')
[1] "MTH314" "LB471"  "PHY472"
  • Related