2016-11-16 44 views
0

我在数据库表中有一个值,我想分割|值为Company|company.pdf|images.pdf。当我运行下面的代码时,它只会在调试中返回C分割数组后只给出第一个字符

我在做什么错?

 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); 
     while(catGetGeneralNameQuery.moveToNext()){ 
      String name = catGetGeneralNameQuery.getString(catGetGeneralNameQuery.getColumnIndex("value")); 
      String[] separated = name.split("|"); 
      Log.d("LOG", separated[1]); 
     } 

回答

1

这是因为该方法split()采取正则表达式作为参数,并|是在正则表达式保留字符。

尝试使用:\\|来逃避它。

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

它输出:

company.pdf 

参见split()方法文档:https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

管道(没有被转义)中的正则表达式是用来分隔备用匹配模式,例如:aaa|bbb将匹配“aaa”或“bbb”,这就是为什么在不逃脱时它匹配每个单独的字符。

希望它有帮助。

1

您需要逃离原来的特殊字符:

String[] separated = name.split("\\|"); 
0

使用: 的String [] B = a.split( “\\ |”);

它可以正常工作