Java - String separates each character

When I try to split the line with the separator "|", it seems to split every single character.

This is my line that causes the problem:

String out = myString.split("|"); 
+6
source share
3 answers

In regex | - The reserved character used for alternation . You need to avoid this:

 String out = string.split("\\|"); 

Notice that we used two backslashes. This is because the first one avoids the second in the Java string, so the string passed to the regex engine is \| .

+15
source

I think Java already answered that splitting a string into an array

In a summary of the answers in the link above:

 String[] array = values.split("\\|",-1); 

This is because:

This method works as if it were calling a method with two split arguments with a given expression and a limit argument with zero. Therefore, trailing blank lines are not included in the resulting array.

+1
source

split takes a regular expression in which | is a special character. You need to avoid this with a backslash. But the backslash is a special character in Java strings, so you need to avoid that too.

 myString.split("\\|") 
+1
source

Source: https://habr.com/ru/post/976248/


All Articles