14

I'm trying to trim the @domain.xxx from email address leaving just the username. I'm not sure how to dynamically select the @ position and everything to the right of it. Could someone please provide an example of how to do this? The trim code below is where I'm lost.

email = "example@domain.com"
email....(trim code);
email.replace(email, "");
Code Junkie
  • 7,602
  • 26
  • 79
  • 141
  • Can you rely on valid email address? – Gaim Apr 30 '12 at 15:16
  • there should be sort of `explode()` function which would take `@` as input and return an array of two elements: `example` and `domain.com`. – ᴍᴇʜᴏᴠ Apr 30 '12 at 15:17
  • 1
    @The Sexiest Man in Jamaica That method is called `email.split('@')` – Gaim Apr 30 '12 at 15:21
  • take a look at http://stackoverflow.com/questions/5214372/getting-only-email-address-to-display-when-using-message-getfrom-in-javamail http://docs.oracle.com/javaee/6/api/javax/mail/internet/InternetAddress.html – V H Feb 02 '17 at 18:19

3 Answers3

41

To find: int index = string.indexOf('@');

To replace: email = email.substring(0, index);

To summarize:

email = "example@domain.com";
int index = email.indexOf('@');
email = email.substring(0,index);
gcochard
  • 11,408
  • 1
  • 26
  • 41
  • Thanks Greg, this is exactly what I was looking for. Thanks for the explanation too, I now know how to handle things like this dynamically now. – Code Junkie Apr 30 '12 at 15:21
12

Another approach is to split an email on a nickname and on a domain. Look at javadoc

There is a code example:

String email = "example@domain.com";
String[] parts = email.split('@');

// now parts[0] contains "example"
// and parts[1] contains "domain.com"
Gaim
  • 6,734
  • 4
  • 38
  • 58
0

In Kotlin

email = "example@domain.com"
username = email.takeWhile{ it != '@' }
Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35