Home > Back-end >  Regex to match number between 2 last hyphens
Regex to match number between 2 last hyphens

Time:10-04

How to macth the numbers between the 2 last hyphens in a string?

Examples:

abcd-fghi-0123-jklm-5555-789 - match 5555
abcde-987-fghij-678-54321 - match 678

CodePudding user response:

You can use lookarounds:

(?<=-)\d (?=-[^-]*$)

(?<=-) is a lookbehind for -, so this requires there to be a - before the number. (?=[^-]*$) is a lookahead that requires the number to be followed by a -, a sequence of non-hyphen characters, and the end of the string.

DEMO

CodePudding user response:

  1. If your regex flavor supports lookarounds (lookbehind and lookahead) then something like this:

    (?<=-)[^-](?=-[^-]$)

  2. If it does not support them, then you'll need to look inside capturing group 1 to get it with this:

    (?:-([^-])-[^-]$)

  • Related