Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get String.split() to work as expected on android

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"
like image 576
Nguyen Minh Binh Avatar asked Dec 06 '22 20:12

Nguyen Minh Binh


1 Answers

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.

like image 96
Nicole Avatar answered Dec 10 '22 13:12

Nicole