Splitting string with pipe character ("|")

JavaRegex

Java Problem Overview


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

Java Solutions


Solution 1 - Java

| is a metacharacter in regex. You'd need to escape it:

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

Solution 2 - Java

##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 ]

Solution 3 - Java

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.

Solution 4 - Java

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

Solution 5 - Java

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);
		
	}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGiridharanView Question on Stackoverflow
Solution 1 - JavadevnullView Answer on Stackoverflow
Solution 2 - JavaPrateekView Answer on Stackoverflow
Solution 3 - JavaMarounView Answer on Stackoverflow
Solution 4 - JavaAnirudhaView Answer on Stackoverflow
Solution 5 - JavaKickView Answer on Stackoverflow