1

Consider a pair of IPv4 or IPv6 address and port, separated by either / or :, e.g.

10.10.10.10:1234

The port is optional, so strings like

10.10.10.10/
10.10.10.10:
10.10.10.10

are also valid. The address/port pair may be followed by space or comma characters and it is part of a much longer enclosing string.

What would be a very simple regex to extract the 2 values in separate fields from the enclosing string (without using String manipulation functions)?

For example, an expression like

(?<address>[^\s,]+[^\s,:\.])((/|:)(?<port>\d*))?

extracts both address and port in the same string.

The goal here is to achieve extraction with the simplest possible regex, even if it is not 100% accurate (i.e., even if it matches other strings as well).

3
  • If it's not a problem if it is simple and long, check this (no port but can be appended) stackoverflow.com/questions/23483855/… Commented Apr 20, 2015 at 20:11
  • Why a regex? Regular String methods are better here Commented Apr 20, 2015 at 20:21
  • I have seen many such regular expressions, but looking for a simple one. :-) Commented Apr 20, 2015 at 20:24

2 Answers 2

2
([0-9.]*)(\/|:)([0-9]*)

Here is the regex . First group gives you IP. Third group gives you the Port number. Middle group gives separator i.e / or : used for alternation. It can be ignored.

Sign up to request clarification or add additional context in comments.

7 Comments

It works fine for IPv4 but does not cover IPv6. Thanks and +1.
could you give me a sample for IPv6 address ?
IPV6 addresses contain numbers [0-9], letters [A-F] and : symbols, e.g. 1234:ab8:46a3::2a8e:567:1234 is an IPv6 address.
okay. is the number of colons : fixed before the port number colon ?i.e 4 ?
No, it can be any number, from 0 to quite a few and you can never know how many exactly.
|
1

Use commons validator:

InetAddressValidator validator = InetAddressValidator.getInstance();
if (validator.isValid(ipAddress) {
   // cool, isn't valid
}
throw new InvalidAddressException(ipAddress);

2 Comments

Regular expressions are not the way to go here, PNS.
They are the only way. The address/port pair is extracted from a long string, as I say in the question, and that long string also has other fields that nee to be extracted. So, the regular expression I asked for will be part of a much longer one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.