Regex: Match first two digits of a four digit number

Viewed 114

I have:

'30Jun2021'

I want to skip/remove the first two digits of the four digit number (or any other way of doing this):

'30Jun21'

I have tried:

^.{0,5}

https://regex101.com/r/hAJcdE/1

I have the first 5 characters but I have not figured out how to skip/remove the '20'

4 Answers

Manipulating datetimes is better using the dedicated date/time functions.

You can convert the variable to date and use format to get the output in any format.

x <- '30Jun2021'
format(as.Date(x, '%d%b%Y'), '%d%b%y')
#[1] "30Jun21"

You can also use lubridate::dmy(x) to convert x to date.

You don't even need regex for this. Just use substring operations:

x <- '30Jun2021'
paste0(substr(x, 1, 5), substr(x, 8, 9))

[1] "30Jun21"

You could also match the format of the string with 2 capture groups, where you would match the part that you want to omit and capture what you want to keep.

\b(\d+[A-Z][a-z]+)\d\d(\d\d)\b

Regex demo

sub("\\b(\\d+[A-Z][a-z]+)\\d\\d(\\d\\d)\\b", "\\1\\2", "30Jun2021")

Output

[1] "30Jun21"

Use sub

 sub('\\d{2}(\\d{2})$', "\\1", x)
[1] "30Jun21"

or with str_remove

library(stringr)
str_remove(x, "\\d{2}(?=\\d{2}$)")
[1] "30Jun21"

data

x <- '30Jun2021'
Related