Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string on the double pipe(||) using String.split()

Tags:

java

split

I'm trying to split the string with double pipe(||) being the delimiter.String looks something like this:

String str ="[email protected]||[email protected]||[email protected]";

i'm able to split it using the StringTokeniser.The javadoc says the use of this class is discouraged and instead look at String.split as option.

StringTokenizer token = new StringTokenizer(str, "||");

The above code works fine.But not able to figure out why below string.split function not giving me expected result..

String[] strArry = str.split("\\||");

Where am i going wrong..?

like image 902
FarSh018 Avatar asked Mar 20 '13 13:03

FarSh018


People also ask

When to use the split string technique?

This technique is used when there is a multiple character through which we would like to split the string. For example, in a message log, let us say a particular string is occurring after every sentence instead of a full stop.

What is the use of split method in JavaScript?

The split method returns the new array. Also, when the string is empty, split returns an array containing one empty string, rather than an empty array. On compiling, it will generate the same code in JavaScript.

How to split strings by a specific separator function in go?

There are many ways to split strings by a specific separator function in Go. Below are some of the easy ways of doing string splitting in GoLang. 1. Split String using the split() function . The strings package contains a function called split(), which can be used to split string efficiently. The method usage is shown below.

What is the location of split in a string?

Now one thing to watch out for is the location of split of a string. This might be a single character or even combination of multiple characters. The location or the pattern on which it is decided to split the string is known as delimiter.


2 Answers

String.split() uses regular expressions. You need to escape the string that you want to use as divider.

Pattern has a method to do this for you, namely Pattern.quote(String s).

String[] split = str.split(Pattern.quote("||"));
like image 124
Gijs Overvliet Avatar answered Sep 27 '22 21:09

Gijs Overvliet


You must escape every single | like this str.split("\\|\\|")

like image 43
gtgaxiola Avatar answered Sep 27 '22 21:09

gtgaxiola