Home > database >  Extract second last IP address from a list of IP using RegEx
Extract second last IP address from a list of IP using RegEx

Time:09-16

I want to extract the second last IP address from the below expression using regex:

18.223.194.15, 56.99.45.32, 32.65.27.65, 52.89.22.5, 123.12.22.53

Should get 52.89.22.5 from the above

16.45.98.14, 10.22.102.16

Should get 16.45.98.14 from the above

I was able to get the last IP or the first IP using the below regex commands but I am having trouble getting the second last ip

To get the last IP

(?<IP>([0-9]{1,3}\.){3}[0-9]{1,3}) $

To get the first IP

(?<IP>([0-9]{1,3}\.){3}[0-9]{1,3}),.*

Thanks in advance

CodePudding user response:

You need a regex flavour with some form of lookahead/lookbehind.

This could take the form of a capture group surrounded by something.

Assume regex has basic form: ^A(xA)*$ or ^(Ax)*A$

A is something of interest. x is a separator.

  • for final A: ^(Ax)*(A)$
  • for 2nd-to-last A: ^(Ax)*(A)xA$
  • for (n 1)th-to-last A: ^(Ax)*(A)(xA){n}$

In all cases, result is in second capture group.

CodePudding user response:

You can capture the second last one, and match the last one asserting the end of the string after it.

\b(?<IP>(?:[0-9]{1,3}\.){3}[0-9]{1,3}), (?:[0-9]{1,3}\.){3}[0-9]{1,3}$

See a regex demo.

  • Related