conditionally removing first two letter of every entry in a string in R

Viewed 31

I have a vector with some codes. However, for an unknown reason, some of the code start with X# (# being a number 0-9). If my vector item does start with x#, I need to remove the first two letters.

Examples:

codes <- c('x0fa319-432f39-4fre78', '23weq0-4fsf198-417203', 'x2431-5435-1242-qewf')
expectedResult <- c('fa319-432f39-4fre78', '23weq0-4fsf198-417203', '431-5435-1242-qewf')

I tried using str_replace and gsub, but I couldn't get it right:

gsub("X\\d", "", codes)

but this would remove the x# even if it was in the middle of the string.

Any ides?

1 Answers

You can use

codes <- c('x0fa319-432f39-4fre78', '23weq0-4fsf198-417203', 'x2431-5435-1242-qewf')
sub("^x\\d", "", codes, ignore.case=TRUE)

See the R demo.

The ^x\d pattern matches x and any digit at the start of a string.

sub replaces the first occurrence only.

ignore.case=TRUE enables case insensitive matching.

Related