Rubin
Rubin

Reputation: 57

How to split string to a specific pattern?

I have address on String with this format: http://171.1.1.1:8080/ , I want to use in the code the ip and the port separately. I did it in this way. but it's really look like hard code.

String[] hostAndPort = address.replace("http://", "").replace("/", "").split(":");

I need another idea with a nicer way.

Upvotes: 1

Views: 94

Answers (2)

Amit Gold
Amit Gold

Reputation: 767

You should use the URI, but it's worth pointing out that regexes can help in such situations.

Upvotes: 0

mzc
mzc

Reputation: 3355

You could use the JDK's URI class:

final URI uri = URI.create("http://127.0.0.1:8080/a/b");
System.out.println(uri.getHost()); // 127.0.0.1
System.out.println(uri.getPort()); // 8080

Upvotes: 4

Related Questions