-1

I'm very new to regular expressions and I'm have some trouble putting them together at the moment. I'm working with R at the moment, and I'm looking to ensure all strings in a character vector are of length 3.

So say I have a character vector of the following:

['1','23','113']

What regular expression would I be able to use to ensure that the length of each string is 3 and in the cases where it is less, add 0's to the start?

So the output I would be looking for would be:

['001','023','113']

An explanation alongside the answer would be really appreciated, thanks.

Edit: The length of strings in the character vector will be greater than or equal to 1 and less than or equal to 3.

Isaac
  • 1,371
  • 3
  • 14
  • 36

1 Answers1

3

Instead of regex, I would look at the sprintf function:

x <- c(1, 23, 113)
x
# [1]   1  23 113
sprintf("%03d", x)
# [1] "001" "023" "113"

As you are dealing with a character vector, you would probably need to use as.numeric first:

X <- as.character(x)
sprintf("%03d", X) ## Won't work
# Error in sprintf("%03d", X) : 
#   invalid format '%03d'; use format %s for character objects
sprintf("%03d", as.numeric(X))
# [1] "001" "023" "113"
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485