Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java .split("|") not working

Tags:

java

string

split

I just ran into the problem that the split method for strings wouldn't work with character "|" as an argument. It somehow separates each character in the string.

Code:

String[] res = "12345|6".split("|");
Log.d("split", Arrays.toString(res));

Output:

split﹕ [, 1, 2, 3, 4, 5, |, 6]
like image 569
LordBullington Avatar asked Sep 22 '15 11:09

LordBullington


People also ask

Why is my split method not working in Java?

1.1. Method Syntax The split () method is overloaded: Watch out that split () throws PatternSyntaxException if the regular expression’s syntax is invalid. In given example, " [" is invalid regular expression. Program output. Method does not accept 'null' argument.

What is string split () method in Java?

The string split () method breaks a given string around matches of the given regular expression. For Example: Input String: 016-78967 Regular Expression: - Output : {"016", "78967"} Following are the two variants of split () method in Java: 1. Public String [ ] split ( String regex, int limit )

Does string split work on Dot in Java?

string - The split () method in Java does not work on a dot (.) - Stack Overflow Bookmark this question. Show activity on this post. How can I use "." as the delimiter with String.split () in java [duplicate] (8 answers)

How to split string into array in Java with delimiter?

In this tutorial, learn how to split a string into an array in Java with the delimiter. 1. String split () Method Use split () to split a string into a string array by tokenizing with delimiter or regular expression. 1.1. Method Syntax The split () method is overloaded:


1 Answers

Use escape character before | like below:

String[] res = "12345|6".split("\\|");

Similar "escape character logic" is required, when you are dealing/splitting with any of the below special characters (used by Regular Expression):

  • OR sign (|)
  • question mark (?)
  • asterisk (*)
  • plus sign (+)
  • backslash (\)
  • period (.)
  • caret (^)
  • square brackets ([ and ])
  • dollar sign ($)
  • ampersand (&)
like image 188
developer Avatar answered Oct 11 '22 23:10

developer