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
You can try using the following regular expression.
Link to expression to try out.
Breaking the expression down:
Here are two ways to do that.
Use K
Match
Demo
The component parts of the expression are as follows.
Use a capture group
Match
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".