maniA
maniA

Reputation: 1457

Repeating a regex pattern for date parsing

I have the following string

"31032017"

and I want to use regular expressions in R to get

"31.03.2017"

What is the best function to do it? And a general question, how can I repeat the matched part, like as in sed in bash? There, we use \1 to repeat the first matched part.

Upvotes: 0

Views: 122

Answers (2)

AEF
AEF

Reputation: 5670

You need to put the single parts in round brackets like this:

sub("([0-9]{2})([0-9]{2})([0-9]{4})", "\\1.\\2.\\3", "31032017")

You can then use \\1 to access the part matched by the first group, \\2 for the second and so on.

Note that if your string is a date, there are better ways to parse / reformat it than directly using regex.

Upvotes: 3

Andre Elrico
Andre Elrico

Reputation: 11490

date_vector = c("31032017","28052017","04052022")

as.character(format(as.Date(date_vector, format = "%d%m%Y"), format = "%d.%m.%Y"))

#[1] "31.03.2017" "28.05.2017" "04.05.2022"

If you want to work/do math with dates, omit as.character.

Upvotes: 3

Related Questions