R: remove substring and change the remaining string by addition of a number

Viewed 64

in R: I have some strings with the following pattern of letters and numbers

A11B3XyC4
A1B14C23XyC16
B14C23XyC16D3
B14C23C16D3

I want to remove the part "Xy" (always the same letters) and when I do this I want to increase the number behind the Letter B by one (everything else should stay the same). When there is no "Xy" in the string there is no change to the string The result should look like this:

A11B4C4
A1B15C23C16
B15C23C16D3
B14C23C16D3

Could you point me to a function capable of this? I struggle with doing a calculation (x+1) with a string.

Thank you!

1 Answers

We could use str_replace to do the increment on the substring of numbers that follows the 'B' string after removing the 'Xy' only for cases where there is 'Xy' substring in case_when

library(stringr)
library(dplyr)
case_when(str_detect(str1, "Xy") ~ str_replace(str_remove(str1, 
   "Xy"), "(?<=B)(\\d+)", function(x) as.numeric(x) + 1), TRUE  ~str1)
[1] "A11B4C4"     "A1B15C23C16" "B15C23C16D3" "B14C23C16D3"

data

str1 <- c("A11B3XyC4", "A1B14C23XyC16", "B14C23XyC16D3", "B14C23C16D3")
Related