简体   繁体   English

使用 RegEx 从 IP 列表中提取倒数第二个 IP 地址

[英]Extract second last IP address from a list of IP using RegEx

I want to extract the second last IP address from the below expression using regex:我想使用正则表达式从下面的表达式中提取倒数第二个 IP 地址:

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应该从上面得到 52.89.22.5

16.45.98.14, 10.22.102.16

Should get 16.45.98.14 from the above应该从上面得到 16.45.98.14

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我能够使用以下正则表达式命令获得最后一个 IP 或第一个 IP 但我无法获得倒数第二个 ip

To get the last IP获取最后一个 IP

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

To get the first IP获得第一个 IP

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

Thanks in advance提前致谢

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 .查看正则表达式演示

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(xA)*$^(Ax)*A$

A is something of interest. A是有趣的东西。 x is a separator. x是分隔符。

  • for final A : ^(Ax)*(A)$最后A : ^(Ax)*(A)$
  • for 2nd-to-last A : ^(Ax)*(A)xA$对于倒数第二个A^(Ax)*(A)xA$
  • for (n+1)th-to-last A : ^(Ax)*(A)(xA){n}$对于倒数第 (n+1) 个A : ^(Ax)*(A)(xA){n}$

In all cases, result is in second capture group.在所有情况下,结果都在第二个捕获组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM