What is the best way in R to identify the first character in a string?

Viewed 799

I am trying to find a way to loop through some data in R that contains both numbers and characters and where the first character is found return all values after. For example:

column 
000HU89
87YU899 
902JUK8   

result
HU89
YU89 
JUK8

have tried stringr_detct / grepl but the value of the first character is by nature unknown so I am having difficultly pulling it out.

4 Answers

We could use str_extract

stringr::str_extract(x, "[A-Z].*")
#[1] "HU89"  "YU899" "JUK8" 

data

x <- c("000HU89", "87YU899", "902JUK8")

Ronak's answer is simple. Though I would also like to provide another method:

column <-c("000HU89", "87YU899" ,"902JUK8")
# Get First character
first<-c(strsplit(gsub("[[:digit:]]","",column),""))[[1]][1]
# Find the location of first character
loc<-gregexpr(pattern =first,column)[[1]][1]
# Extract everything from that chacracter to the right
substring(column, loc, last = 1000000L)

We can use sub from base R to match one or more digits (\\d+) at the start (^) of the string and replace with blank ("")

sub("^\\d+", "", x)
#[1] "HU89"  "YU899" "JUK8" 

data

x <- c("000HU89", "87YU899", "902JUK8")

In base R we can do

x <- c("000HU89", "87YU899", "902JUK8")
regmatches(x, regexpr("\\D.+", x))
# [1] "HU89"  "YU899" "JUK8" 
Related