Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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: /(?:(?: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})/

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
321 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

(?::                #Match the :
  (?![7-9]dddd) #Ignrore anything above 7....
  (?!6[6-9]ddd)  #Ignore anything abovr 69...
  (?!65[6-9]dd)   #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(
    '/(?:(?: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]dddd) #Ignrore anything above 7....
      (?!6[6-9]ddd)  #Ignore anything abovr 69...
      (?!65[6-9]dd)   #etc...
      (?!655[4-9]d)
      (?!6553[6-9])
      (?!0+)            #ignore complete 0(s)
      (?P<Port>d{1,5})
    )?
    /x', 
    $subject)) {
    # Successful match
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...