chitti
chitti

Reputation: 121

split hostname and domain name from fqdn using regex

I am working on regular expression. i.e java.google.com here "java" is hostname and "google.com" is domain name. Now I would like to extract from

String fqdn = "java.google.com";

String hostname = "java";
String domain = "google.com";

using regex.

I tried like this

String text = "java.google.com";
String extensionRemoved = text.split("\\.")[0];

I am getting result as java. But I want some regex which should give me "java" separate string and "google.com" separate String.

I can use StringTokenizer but I don't want to use StringTokenizer as it effect performance If I have 1000,1,00,000 records from db. Thanks if any one gives efficient solution for this.

Upvotes: 0

Views: 5280

Answers (3)

gervais.b
gervais.b

Reputation: 2347

For this kind of simple parsing, indexOf and substring will be more efficient.

edit But if you really want a regex then this one is basic but do it ˋ(\w+).([.\w]+)ˋ the ˋgroup(1)contains the hostname and ˋgroup(2) the domain. But some edge cases may not match.

Upvotes: 1

Hugues M.
Hugues M.

Reputation: 20477

Note String.split has a variant that allows you to specify a maximum number of splits:

String[] x = "java.sun.com".split("\\.", 2);
System.out.println(x[0]); // java
System.out.println(x[1]); // sun.com

Upvotes: 2

Abe
Abe

Reputation: 1415

Try this:

String text = "java.google.com";
String domain = text.split("\\.")[0];
String ext = text.replace(domain, "");
System.out.print("Domain:"+domain);
System.out.print("\n");
System.out.print("Ext:"+ext);

Upvotes: 2

Related Questions