Kotlin: How do I get characters after "@" in a string?

Daniel Dramond picture Daniel Dramond · Nov 29, 2017 · Viewed 17k times · Source

I have a string that is an email. I want to be able to get the domain part of the email no matter what the string/email is. Essentially I'm wanting to get hold of the characters after the @ part of the string. For example, for [email protected], I'm after the kotlin.com part.

val emailString = "[email protected]"

Answer

Ivan Wooll picture Ivan Wooll · Nov 29, 2017

While there's nothing wrong with the accepted answer the Kotlin standard library is worth exploring as it contains nice little methods like substringAfterLastwhich would shorten the example to this

val string = "[email protected]"

val domain: String? = string.substringAfterLast("@")