i have numeric values that have nchar = 7 or 8.
For instance let's say I have these two values :
1234567
12345678
what I want do is:
If nchar(x) = 7
then add / after the 1st value and 3rd value.
So, my results would look like this:
1/23/4567
if nchar(x) = 8, then add / after the 2nd and 4th value.
Results: 12/34/5678.
We can use sub here:
x <- "12345678"
sub("(\\d+)(\\d{2})(\\d{4})$", "\\1/\\2/\\3", x)
does it have to be with regex?
how about:
test <- '1234567'
n <- nchar(test)
test_split <- strsplit(test, '')[[1]]
paste0(paste0(test_split[1:(n - 6)], collapse = ''), '/',
paste0(test_split[(n - 5):(n - 4)], collapse = ''), '/',
paste0(test_split[(n - 3):n], collapse = ''))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With