I have a sequence of dates in character ("2018-09-032018-09-09" "2018-09-102018-09-16" .....) and I would add a white space after the 10th digit. As a final result, I would obtain the following "2018-09-03 2018-09-09" "2018-09-10 2018-09-16"...
I guess the gsub fuction can help but I don't know how to implement it
Could you please help me ?
CodePudding user response:
We could use str_extract_all
with this '\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])'
regex which is for YYYY-MM-DD format:
library(stringr)
unlist(str_extract_all(dates, '\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])'))
output:
"2018-09-03" "2018-09-09" "2018-09-10" "2018-09-16"
CodePudding user response:
Does this work:
gsub('(.{10})(.*)','\\1 \\2' ,c("2018-09-032018-09-09", "2018-09-102018-09-16"))
[1] "2018-09-03 2018-09-09" "2018-09-10 2018-09-16"
CodePudding user response:
We can use sub
to capture the first 10 digits and then add the space
sub("^(.{10})(.*)", "\\1 \\2", dates)
-output
[1] "2018-09-03 2018-09-09" "2018-09-10 2018-09-16"
NOTE: We used sub
and that was only necessary along with the fact that i specified the start (^
) character.
data
dates <- c("2018-09-032018-09-09", "2018-09-102018-09-16")