Regex to capture page number from filename

Viewed 79

I have document page images named (for example) as follows:

“2020-07-24 07;17;09 - ABCD - 12345-67890 (14 Main St) - 01 [Declaration 1].png”
“2020-07-24 07;17;09 - ABCD - 12345-67890 (14 Main St) - 02 [Declaration 2].png”
“2020-07-24 07;17;09 - ABCD - 12345-67890 (14 Main St) - 07 [Fire].png”
“2020-07-24 07;17;09 - ABCD - 12345-67890 (14 Main St) - 12 [Fungi etc].png”

I want to capture ONLY the page numbers, without preceding zeros (1, 2, 7, 12 in this example). Based on code I saw here, I thought maybe something like this might take care of it:

 - 0*\d+.*\.(?:jpe?g|png|tiff?)$(?!(?:0*)\d+)

…but, it did not. Any other suggestions?

2 Answers

You could use a capturing group for the digits:

- 0*(\d+) \[[^][]*]\.(?:jpe?g|png|tiff?)\b

Explanation

  • - 0* Match - a space and 0+ times a zero
  • (\d+) Capture group 1, match 1+ digits
  • [[^][]*] Match a space and from [ till ]
  • \.(?:jpe?g|png|tiff?)\b Match a dot and one of the alternatives

Regex demo

To capture the last digits without leading zeroes after the last occurrence of space dash space, you could use a negative lookahead:

 - 0*(\d+)(?!.* - ).*\.(?:jpe?g|png|tiff?)$

Regex demo

So it looks like you want to end up at the last hyphen. Try:

-\h*(?!.*-)0*(\d+)

See the demo


  • -\h* - Match a literal hypen and zero or more horizontal whitespaces.
  • (?!.*-) - A negativ lookahead for zero or more characters and hyphen.
  • 0* - Zero or more zeroes.
  • (\d+) - Capture at least a single digit into capture group 1.

End note: Please give credit where credit is due. Your question did not have the necessary details given later through comments. This answer is far more detailed based on what you provided in the OP.

Related