How to grab IP:PORT with regex?

2019-02-16 19:15发布

问题:

I'm creating a small IP:PORT scraper in PHP. The problem is that I'm pretty unfamiliar with RegEx.

So I've been piecing together what I can.

Here's what I've got: /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):([0-9]{1,5})\b/

I know this isn't the best. At least not the end to grab the port, because it means that ports will be able to be things like 99999.

Also, it seems to return two matches this way. The IP:PORT and the PORT. I just need it to grab the full IP:PORT, not one or the other.

回答1:

I've posted a regular expression below what matches either ip or ip and port.

$ip = '111.222.333.444';
if ( preg_match('/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\:?([0-9]{1,5})?/', $ip, $match) ) {
   echo 'ip: ' . $match['1'] . (isset($match['2']) ? ' port: ' . $match['2'] : '');
}


回答2:

Your regex is fine so I will just concentrate on the port itself. This regex :

(?::                #Match the :
  (?![7-9]\d\d\d\d) #Ignrore anything above 7....
  (?!6[6-9]\d\d\d)  #Ignore anything abovr 69...
  (?!65[6-9]\d\d)   #etc...
  (?!655[4-9]\d)
  (?!6553[6-9])
  (?!0+)            #ignore complete 0(s)
  (?<Port>\d{1,5})
)?

Will optionally catch any valid port number and store it to named group port.

Note: free spacing must be enabled:

if (preg_match(
    '/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
    (?::
      (?![7-9]\d\d\d\d) #Ignrore anything above 7....
      (?!6[6-9]\d\d\d)  #Ignore anything abovr 69...
      (?!65[6-9]\d\d)   #etc...
      (?!655[4-9]\d)
      (?!6553[6-9])
      (?!0+)            #ignore complete 0(s)
      (?P<Port>\d{1,5})
    )?
    \b/x', 
    $subject)) {
    # Successful match
}


回答3:

You could try this:

\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):\d{1,5}\b

There are a few examples for IP matching here. Just take any of them and put :\d{1,5}\b on the end (to match a port).



回答4:

I have used this long time ago.

[0-9]{3}.[0-9]{3}.[0-9]{3}.[0-9]{3}:[0-9]{5}


回答5:

FailedDev's Port portion of his answer - shortened it a bit and set boundaries, this will only catch the port

\b(?![7-9]\d{4})(?!6[6-9]\d{3})(?!65[6-9]\d{2})(?!655[4-9]\d)(?!6553[6-9])(?!0+)(\d{1,5})\b


标签: php regex ip port