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

I want to split an email string in java (android), but it does not work correctly.

Input: " ihnel48@gmail.com " String[] pattens = email.split("@."); Expected: "ihnel48", "gmail", "com" Output: "ihnel48" "mail.com" 
+4
source share
8 answers

Since String.split matches on a regular expression basis, @. means that it searches for two characters in a string (not one character once). And . in regular expressions, it is a special symbol meaning "anything":

 @. = "@ and then any character" 

In your case, this matches "@g" and not a period.

Instead, you want:

 String[] pattens = email.split("[@.]"); 

The square brackets [] create a character class that represents all valid characters that can match a single position. So you need to match " @ " or " . ". Symbol . no need to escape inside a character class.

+11
source

You need to avoid the period ( . ). Otherwise, it is a wildcard and will match any single character. A way to avoid this is with a backslash. In literal strings in Java, the backslash is also an escape character, so you need to use two backslashes. In addition, you need some kind of "or" operator to tell him to split when he gets into . OR a @ . There are two ways to do this.

Here is one:

 String[] pattens = email.split("@|\\."); 

Here is another:

 String[] pattens = email.split("[@\\.]"); 
+3
source

. matches g , i.e. g also deleted

+1
source

It seems to me that it works great. You gave him a regular expression that said he was looking for the @ symbol, followed by any character (which is "." Means in the regular expression). This is what he found and split up.

I am not a regex wonk, but I think it might be "@ | \". will do what you apparently intended.

0
source

Try:

 String[] pattens = email.split("@"); 
0
source

You wanted to split on @ or. I believe.

The correct regular expression for this is: "@|\."

Edit: put brackets in place of the original quotes

0
source

Fun decision:

  //Replace all "." to "@", and split String split(String input){ String[] patterns = input.replaceAll("\\.", "@").split("@"); return Arrays.toString(patterns); } 
0
source

try this code

  StringTokenizer tokens = new StringTokenizer(CurrentString, "@"); String first = tokens.nextToken(); String second = tokens.nextToken(); 
0
source

All Articles