rannoudanames
rannoudanames

Reputation: 139

R gsub regular expression syntax error

If I have some string : 2017-01-12T19:00:00.000+000, and I want to have 2017-01-12, so delete all after and including "T" How do I proceed,

gsub("$.*T"," ","2017-01-12T19:00:00.000+000")

, would this not work? I am referring my self to:http://www.endmemo.com/program/R/gsub.php

Thank you!

Upvotes: 0

Views: 257

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521179

One approach is to match and capture the date portion of your string using gsub() and then replace the entire string with what was captured.

gsub("(\\d{4}-\\d{2}-\\d{2}).*","\\1","2017-01-12T19:00:00.000+000")
[1] "2017-01-12"

Your original approach:

gsub("T.*","","2017-01-12T19:00:00.000+000")
[1] "2017-01-12"

As others have said, if the need for this format exceeds the scope of this particular timestamp string, then you should consider using a date API instead.

Demo here:

Rextester

Upvotes: 1

Related Questions