Regex pulling IP and port from string

此生再无相见时 提交于 2021-01-28 02:01:22

问题


I'm using Perl to try and pull the IP address and port from a string.

The regex I'm trying to use is:

s/(sip:)(;.*)//

The strings are:

  • sip:255.255.255.255:8080;transport=TCP
  • sip:255.255.255.255:8080

Obviously my regex replace is not working. Can anyone point me to how I would need to write the regex? From those two strings I want to pull this:

255.255.255.255:8080

Meaning the regex needs to match anything that's not that string and replace it with nothing.

Note: IP address and port will be different every time.


回答1:


You can use the following:

/((\d{1,3}.){3}\d{1,3}:\d+)/

Explanation:

(\d{1,3}\.){3} : between 1 and 3 consecutive digits followed by a period 3 times in a row \d{1,3}:\d+ : between 1 and 3 consecutive digits followed by a colon followed by at least 1 digit

So in code it would look something like this:

my $s = 'sip:255.255.255.255:8080;transport=TCP';
my ($socket) = $s =~ /((\d{1,3}.){3}\d{1,3}:\d+)/;



回答2:


Here is a solution that uses the Regexp::Common library to match the IP address.

use 5.022;
use Regexp::Common qw/net/;

while (<DATA>){
    my @matches = ($_ =~ m/^sip:$RE{net}{IPv4}{-keep}:(\d+);?/);
    my $ip = $matches[0].':'. $matches[5];
    say $ip
}

__DATA__
sip:255.255.255.255:8080;transport=TCP
sip:255.255.255.255:8080



回答3:


It's not bulletproof, but this should work:

my $test = 'sip:255.255.255.255:8080;transport=TCP';

my ($ip) = $test =~ /(\d+\.\d+\.\d+\.\d+:\d+)/;

print "$ip\n";

This just extracts it, of course... you could always replace it this way:

$test = $ip;



回答4:


the regular expression tries to match your whole string which does not work since the wanted part is in between the parts you want to remove. so you either need 2 regular expressions to remove first the start and then the end or you need to use capture groups to get the part you want and replace with the captured part like this (not checked for correctness):

s/sip:(.*);.*/$1/


来源:https://stackoverflow.com/questions/34438566/regex-pulling-ip-and-port-from-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!