-3

So i want to match the first number and the last four numbers using regex.

I am able to get the last 4 numbers using \d(?=\d{4}) but unable to get the first and last four numbers together. Tried multiple combinations.

1 Answers1

0

String with Numbers and other characters

^.*?(\d).*(\d).*?(\d).*?(\d).*?(\d).*?$

See the demo

Captures the first number in the string, and then captures the last 4 numbers (all individually, allowing any characters in between).

Breakdown:

  • ^.*? - Lazily match everything
  • (\d) - until it encounters and captures the first number
  • .* - Greedily match everything
  • (\d).*?(\d).*?(\d).*?(\d).*?$ - until it encounters the last 4 numbers with anything in between them, capturing only the numbers. ($ for the end of the string)

Just Numbers

If instead you want to capture these with numbers only:

^(\d)\d+(\d{4})$

See the demo

KyleFairns
  • 2,947
  • 1
  • 15
  • 35