posts - 3, comments - 15, trackbacks - 0, articles - 26
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

String.split(String a)的错误 == 正则表达式问题

Posted on 2005-06-17 11:15 morcble的blog 阅读(767) 评论(0)  编辑  收藏 所属分类: Java

String的静态方法split(String a)有点问题,列如
String a0 = "|we|r|";
String[] b0 = a0.split("|");
b0不会得到预期的数组,而是{"|","w","e","r","|"}.

于是写了一个类代替这个方法
如下
public class Strings {
 public static  Collection seperateBy(String target,String seperate) {
      if (target==null||seperate==null||target.equals("")){
       return new ArrayList();
      }
      Collection collection = new ArrayList();
      int num = target.indexOf(seperate);
      if (num!=-1){
       if(num==0){
        target = target.substring(1,target.length());
            Collection here = seperateBy(target,seperate);
            for(Iterator iterator1 = here.iterator();iterator1.hasNext();){
             collection.add(iterator1.next());
            }
            return collection;
         }
       else if(num == target.length()-1){
        collection.add(target.substring(0,target.length()-1));
        return collection;
       }
       else
       {
        collection.add(target.substring(0,num));
        target = target.substring(num+1,target.length());
        Collection here = seperateBy(target,seperate);
           for(Iterator iterator1 = here.iterator();iterator1.hasNext();){
            collection.add(iterator1.next());
           }
           return collection;
       }
      }
      else collection.add(target);
      return  collection;
     }
/*测试
 public static  void main(String[] args) {
  Collection a1 = Strings.seperateBy("|aaa|aa","|");
  Collection a2 =Strings.seperateBy("|aaa|aa|","|");
  Collection a3 =Strings.seperateBy("aaa|aa","|");
  Collection a4 =Strings.seperateBy("aaaaa","|");
  Collection a5 =Strings.seperateBy("|aaa|aa","|");
  Collection a6 =Strings.seperateBy("||||","|");
  Collection a7 =Strings.seperateBy("","|");
 }*/
}



正则表达式问题

正确写法String a0 = "|we|r|";
String[] b0 = a0.split("\\|");


只有注册用户登录后才能发表评论。


网站导航: