How do I insert "-" between the fourth and fifth numbers of 0912345678 like 0912-345678
I have tried the following code:
data_phone_new = readLines("data_phone.txt")
gsub("....()......","-",data_phone_new)
CodePudding user response:
We can use sub()
as follows:
x <- "0912345678"
output <- sub("(?<=^\\d{4})", "-", x, perl=TRUE)
output
[1] "0912-345678"
CodePudding user response:
We can use groupings. We group the first four characters (^.{4})
and replace it with the same group \\1
plus a -
.
sub("(^.{4})", "\\1-", "0912345678")
#> [1] "0912-345678"
Created on 2022-10-05 by the reprex package (v2.0.1)
CodePudding user response:
A non-regex option with stringr::str_sub
:
library(stringr)
x <- "0912345678"
str_sub(x, 5, 4) <- '-'
#> x
#[1] "0912-345678"
Or in base R with substring
:
paste(substring(x, c(1, 5), c(4, nchar(x))), collapse="-")
#[1] "0912-345678"