[java] Splitting string with pipe character ("|")

I'm not able to split values from this string:

"Food 1 | Service 3 | Atmosphere 3 | Value for money 1 "

Here's my current code:

String rat_values = "Food 1 | Service 3 | Atmosphere 3 | Value for money 1 ";
String[] value_split = rat_values.split("|");

Output

[, F, o, o, d, , 1, , |, , S, e, r, v, i, c, e, , 3, , |, , A, t, m, o, s, p, h, e, r, e, , 3, , |, , V, a, l, u, e, , f, o, r, , m, o, n, e, y, , 1, ]

Expected output

Food 1
Service 3
Atmosphere 3
Value for money 1

This question is related to java regex

The answer is


Or.. Pattern#quote:

String[] value_split = rat_values.split(Pattern.quote("|"));

This is happening because String#split accepts a regex:

| has a special meaning in regex.

quote will return a String representation for the regex.


split takes regex as a parameter.| has special meaning in regex.. use \\| instead of | to escape it.


String rat_values = "Food 1 | Service 3 | Atmosphere 3 | Value for money 1 ";
    String[] value_split = rat_values.split("\\|");
    for (String string : value_split) {

        System.out.println(string);

    }

Using Pattern.quote()

String[] value_split = rat_values.split(Pattern.quote("|"));

//System.out.println(Arrays.toString(rat_values.split(Pattern.quote("|")))); //(FOR GETTING OUTPUT)

Using Escape characters(for metacharacters)

String[] value_split = rat_values.split("\\|");
//System.out.println(Arrays.toString(rat_values.split("\\|"))); //(FOR GETTING OUTPUT)

Using StringTokenizer(For avoiding regular expression issues)

public static String[] splitUsingTokenizer(String Subject, String Delimiters) 
{
     StringTokenizer StrTkn = new StringTokenizer(Subject, Delimiters);
     ArrayList<String> ArrLis = new ArrayList<String>(Subject.length());
     while(StrTkn.hasMoreTokens())
     {
       ArrLis.add(StrTkn.nextToken());
     }
     return ArrLis.toArray(new String[0]);
}

Using Pattern class(java.util.regex.Pattern)

Arrays.asList(Pattern.compile("\\|").split(rat_values))
//System.out.println(Arrays.asList(Pattern.compile("\\|").split(rat_values))); //(FOR GETTING OUTPUT)

Output

[Food 1 ,  Service 3 ,  Atmosphere 3 ,  Value for money 1 ]