Bart Lizak
Bart Lizak

Reputation: 85

Regex: Getting middle digits from another digit

My string (a line, actually) looks like this:

abc bsdb kms 324 kdf 12345678

I want to get a 3rd to 5th number from the number at the end of the line. It's always at the end of the line and it has fixed number of 8 digits.

Desired result:

345

Is that possible?

Upvotes: 0

Views: 932

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

This is the regex to use:

\b\d{2}(\d{3})\d{3}$

Group 1 will hold the 345 value.

To be able to capture values at the end of lines, just use multiline option.

See (updated) demo

Upvotes: 2

karthik manchala
karthik manchala

Reputation: 13640

You can use the following to match:

(\d{3})\d{3}$

and extract the required group by $1 or \1

Explanation:

  • match six digits from the end $ and capture first three (since your length is fixed to 8 it matches middle 3 numbers)

See DEMO

Upvotes: 1

Related Questions