Search code examples
regexmatchdigits

Regex is possible to match?


I have files with these filename:

ZATR0008_2018.pdf
ZATR0018_2018.pdf
ZATR0218_2018.pdf

Where the 4 digits after ZATR is the issue number of magazine.

With this regex:

([1-9][0-9]*)(?=_\d)

I can extract 8, 18 or 218 but I would like to keep minimum 2 digits and max 3 digits so the result should be 08, 18 and 218.

How is possible to do that?


Solution

  • You may use

    0*(\d{2,3})_\d
    

    and grab Group 1 value. See the regex demo.

    Details

    • 0* - zero or more 0 chars
    • (\d{2,3}) - Group 1: two or three digits
    • _\d - a _ followed with a digit.

    Here is a PCRE variation that grabs the value you need into a whole match:

    0*\K\d{2,3}(?=_\d)
    

    See another regex demo

    Here, \K makes the regex engine omit the text matched so far (zeros) and then matches 2 to 3 digits that are followed with _ and a digit.