I want to split an email string in java (android) but it not work correctly.
Input: "[email protected]"
String[] pattens = email.split("@.");
Expected: "ihnel48", "gmail", "com"
Output: "ihnel48" "mail.com"
Because String.split
matches based on a regular expression, @.
means it looks for two characters in a row (not either character once). And, .
in regular expressions is a special character meaning "anything":
@. = "@ and then any character"
In your case this matches "@g" and not the dot.
Instead, you want:
String[] pattens = email.split("[@.]");
The square brackets, []
, create a character class, which represents all the valid characters a single position can match. So, you need to match "@
" or ".
". The character .
does not need to be escaped inside a character class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With