skip to Main Content

I want to match/extract the last 4 consecutive digits in a string. The pattern I need to match is therefore [0-9]{4}, but only the last instance of it in the string – if there are any non-numbers in between, it should match the next instance instead.

Some examples:

ABC123456789A9876  // should extract 9876
ABCD1234567890F23  // should extract 7890
1234ABC4567JIJLMN  // should extract 1234
ABCDEFG1234-!.567  // should extract 1234

How can I accomplish this using regex? Alternatively if there’s an easier way to do this programmatically with PHP/Laravel I’d also be open to it.

2

Answers


  1. You can try using the following regular expression.

    .+(d{4})D?|^(d{4})
    

    Link to expression to try out.

    Breaking the expression down:

    .+(d{4})D?          // match any sequence of 4 digits in the middle
    |                     // or
    ^(d{4})              // match 4 digits at start of string
    
    Login or Signup to reply.
  2. Here are two ways to do that.

    Use K

    Match

    .*Kd{4}
    

    Demo

    The component parts of the expression are as follows.

    .*     # match zero or more characters other than line
           # terminators, as many as possible
    K     # reset the start of the match and discard all
           # previously-consumed characters
    d{4}  # match 4 digits
    

    Use a capture group

    Match

    .*(d{4})
    

    and extract the four digits from capture group 1.

    Demo

    The expression reads, "Match zero or more characters other than line terminators, as many as possible, then then match four digits and save the four digits in capture group 1".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search