Regex: extract numbers between text
10,245
Solution 1
(\d{4}(?=[^\d]))
Use this. It'll look for 4 digits with a non-digit following.
Solution 2
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.
Author by
rookie
Updated on November 28, 2022Comments
-
rookie over 1 year
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:
- extract only digits from the text
- extract only specific number of digits In this case 4) even in the text is given more
- digits (in this case 4) should be extracted backwards
-
d0nut over 8 years@maraca that's what I get for doing regex in the morning I guess xD
-
Avinash Raj over 8 years
(?=[^\d])
equivalent to(?=\D)
-
d0nut over 8 years@AvinashRaj im so glad to hear that
-
Avinash Raj over 8 years@maraca no,
(?=[^\d])
won't match the end of the line boundary but(?!\d)
match the end of the line boundary. -
d0nut over 8 yearsCould we move this discussion to chat or something? I really dont like my phone blowing up with notifications on the technicalities of using one capture group over another at work
-
Simo Erkinheimo over 8 yearsThe OP, and future readers stumbling across this answer, might learn more if you could add some text explaining why this works.