Keith Pi
Keith Pi

Reputation: 21

How to extract part of a domain from a string in Java?

If my domain is 31.example.appspot.com (App Engine prepends a version number), I can retrieve the domain from the Request object like this:

String domain = request.getServerName();
// domain == 31.example.appspot.com

What I want is to extract everything except the version number so I end up with two values:

String fullDomain; // example.appspot.com
String appName;    // example

Since the domain could be anything from:

1.example.appspot.com

to:

31.example.appspot.com

How do I extract the fullDomain and appName values in Java?

Would a regex be appropriate here?

Upvotes: 2

Views: 169

Answers (2)

mohdajami
mohdajami

Reputation: 9680

If you are always sure of this pattern, then just find the first dot and start from there.

fullDomain = domain.subString(domain.indexOf('.'));

UPDATE: after James and Sean comments, here is the full correct code:

int dotIndex = domain.indexOf(".")+1;
fullDomain = domain.substring(dotIndex);
appName = domain.substring(dotIndex,domain.indexOf(".",dotIndex));

Upvotes: 4

brabec
brabec

Reputation: 4730

Take a look at split method on java.lang.String.

Upvotes: 3

Related Questions