Devil Raily Devil Raily - 9 months ago 43
Android Question

After split array gives only first character

I have a value in the database table that I would like to split by

the value is
. When I run the following code, it only returns
in the Debug.

What am I doing wrong?

String cname = null;
String cpdf = null;
String cimages = null;
String catGetGeneralNameSQL = "SELECT * FROM categorymeta WHERE key = 'category_general' AND company = " + dashboard_company_id;
Cursor catGetGeneralNameQuery = myDB.rawQuery(catGetGeneralNameSQL, null);
String name = catGetGeneralNameQuery.getString(catGetGeneralNameQuery.getColumnIndex("value"));
String[] separated = name.split("|");
Log.d("LOG", separated[1]);

Answer Source

It's because the split() method take a regular expression as parameter, and | is a reserved character in regexp.

Try with : \\| to escape it.

public static void main(String[] args) {
  String test = "Company|company.pdf|images.pdf";
  String[] result = test.split("\\|");

It outputs :


See the split() method documentation :

The pipe (without being escaped) is used in regular expressions to separate alternate matching patterns, eg: aaa|bbb will match "aaa" or "bbb", that's why it's matching every single character when not escaped.

Hope it helps.