Doing the match this way may not be a best practice. It might be better to plug into some sort of code with real smarts in it, that can do general-purpose URI parsing. If you have limited needs, though, and can comment/document thoroughly that your code will break if you demand more of it, then maybe it makes sense to go down this path.
The simplest way is to match four sets of 1 to 3 digits, with:
- optionally, one-or-more not-:, plus :, plus one-or-more not-@, plus @
- optionally, :, plus 1 to 5 digits
Something like:
([^:]+:[^@]+@)?(\d{1,3}\.){3}\d{1,3}(:\d{1,5})?
But this would accept silly stuff, like "999.999.999.999:99999"
If you only want to accept valid IP addresses, and don't care that it happens to be part of a URI, or don't care what other garbage exists in the string, here is an example:
http://www.regular-expressions.info/examples.html
It basically matches four sets of:
- 2, plus 0-4, plus 0-9
- or 2, plus 5, plus 0-5
- or 1, plus 0-9, plus 0-9
- or 1-9, plus 0-9
- or 0-9
That should get you started.
- optionally, one-or-more not-:, plus :, plus one-or-more not-@, plus @ (max lengths may be interesting, here)
- optionally, :, plus 0-65535 (this I'll leave up to you, based on the 0-255 rules above)
There are other range-based rules for matching IP addresses that you might want to avoid (stuff like 0.0.0.0, and reserved ranges), but it may be easier to do subsequent matching for these.
Basically, I'd suggest you use the very-simple example, or plug into a library.