Regex get last two digits of year

前端 未结 3 1470
-上瘾入骨i
-上瘾入骨i 2021-01-24 20:51

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 20

相关标签:
3条回答
  • 2021-01-24 21:30

    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.

    0 讨论(0)
  • 2021-01-24 21:33

    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.

    0 讨论(0)
  • 2021-01-24 21:39

    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

    0 讨论(0)
提交回复
热议问题