Code Junkie
Code Junkie

Reputation: 7788

Regex get last two digits of year

I must use regex in order to get the last two digits of a year but only when 4 digits exist. I have the following regex which works perfectly when there is 4 digits. Example 2014 - 14

^.{2}

However I need this to only work when 4 digits are present. I'm having an issue with it emptying my string when only 2 digits exist.

Upvotes: 1

Views: 14838

Answers (3)

hwnd
hwnd

Reputation: 70732

Simply match the four digits and capture only the last two.

^\d{2}(\d{2})$

Then reference capturing group #1 to access your match result.

Upvotes: 8

briantist
briantist

Reputation: 47792

The regex you have there shouldn't be working with 4 digits either. Your regex is looking for any 2 characters at the beginning of the string.

Try this:

(?<=\d\d)\d\d$

Regular expression visualization

Debuggex Demo

This is different from Fede's answer in that you don't need to use and subsequently refer to a capturing group later. Only the last 2 digits are part of the match. It relies on a positive lookbehind.

Upvotes: 1

Federico Piazza
Federico Piazza

Reputation: 30995

You can use this regex.

^(?(?=\d{4}$)..(\d{2}))$

Working demo

This regex uses an IF clause, so if the string is 4 digits then captures the last two.

enter image description here

Upvotes: 1

Related Questions