4

I want to add 0's into the middle of a string until a certain length.

e.g.

AB1
AB2
AB54

Would become:

AB0001
AB0002
AB0054

Thanks

2 Answers 2

5

Using stringr::str_replace extract the numbers from the string and use sprintf to add 0's as prefix.

stringr::str_replace(df$V1, '\\d+', function(m) sprintf('%04s', m))
#[1] "AB0001" "AB0002" "AB0054"

Another way to write the same logic with str_pad instead of sprintf.

library(stringr)
str_replace(df$V1, '\\d+', function(m) str_pad(m, 4, pad = '0'))

data

df <- structure(list(V1 = c("AB1", "AB2", "AB54")), 
      class = "data.frame", row.names = c(NA, -3L))
Sign up to request clarification or add additional context in comments.

Comments

5

For a base R approach, we can try using strsplit on each input using the regex pattern (?<=[A-Z])(?=[0-9]), which will target the split between the letter and numbers potions. Then, we can left pad the number with zeroes to a width of 4 and paste together the two portions.

x <- c("AB1", "AB2", "AB54")
output <- sapply(x, function(x) {
    parts <- strsplit(x, "(?<=[A-Z])(?=[0-9])", perl=TRUE)[[1]]
    paste0(parts[1], sprintf("%04d", as.numeric(parts[2])))
})
output

     AB1      AB2     AB54
"AB0001" "AB0002" "AB0054"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.