rookie
rookie

Reputation: 21

Regex: extract numbers between text

currently I'm using such regex "(\d{4}\b)" in order to extract the numbers. Test string "test 125456 b", so the extract result is "5456".

I wish to get the same result "5456" under the string "test125456b".

I tried to use following regex

((?<!\d)(\d{4})(?!\d))

but it works if only 4 digits (not more) are noted between letters.

So, the aim is:

Upvotes: 1

Views: 11588

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174826

To get the last four digits.

\d{4}(?=\D*$)
  • \d{4} match the four digit character.
  • (?=\D*$) Only if the four digits are followed by a zero or more non-digit characters and the end of the line boundary.
  • So this matches the last 4 digits.

Upvotes: 1

d0nut
d0nut

Reputation: 2834

(\d{4}(?=[^\d]))

Use this. It'll look for 4 digits with a non-digit following.

Regex101

Upvotes: 4

Related Questions