1

I want to split a string by a character sequence, not by a single character. I have this:

String m = "Alcides&|&ola&|&Alcides";
String[] split = m.split("&|&");
System.out.println(split[0] + split[1] + split[2]);

My goal is to have in split[0] -> Alcides and in split[1] -> ola and in split[2] -> Alcides.

But instead the result of the System.out.println is:

Alcides|ola|
Community
  • 1
  • 1

4 Answers4

4

split expects a regex. That means you have to escape the | (which is a logical operator)

String[] split = m.split("&\\|&");
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
3

split takes string representing regex (regular expression).

If you don't know if some character or sequence may be considered as special/meta for regex (like in your case | which represents OR operator, or maybe something like \s which represents all whitespaces) you can use Pattern.quote(yourString) to generate regex which represents only yourString.

So in your case you can use

String[] split = m.split(Pattern.quote("&|&"));
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

| should be escaped because it is used as OR in regular expression:

String m = "Alcides&|&ola&|&Alcides";
String[] split = m.split("&\\|&");
System.out.printf("%s  %s  %s%n", split[0], split[1], split[2] ); // Alcides  ola  Alcides
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
0

Method split takes a string regex as a parameter, where vertical bar character is interpreted as boolean "or". If you don't want to deal with this, you can first replace these sequences: &|& - with something less markedly, for example triple vertical bar delimiter, and then split the string around these delimiters:

String m = "Alcides&|&ola&|&Alcides";
String[] split = m.replace("&|&", "\u2980").split("\u2980");
System.out.println(split[0] + " " + split[1] + " " + split[2]);
// Alcides ola Alcides

See also: How to remove sequence of two elements from array or list?