Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

php - How to grab IP:PORT with regex?

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

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

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...