日期:2014-05-20  浏览次数:20623 次

求助:Java字符串处理
请高手指点
一个字符串格式如下:string = "a=0|b=xxx|c=xxx|d=|e=|f=xxx";
其中a,b,c,d,e,f的值可以为空,要获取a,b,c,d,e,f的值,怎样处理比较好?
我的实现如下:
  String string = "a=0|b=xxx|c=xxx|d=|e=|f=xxx";
  String a = null;
String b = null;
String c = null;
String d = null;
String e = null;
  String f = null;
  String[] content = string.split("\\|");
for(int i=0;i<content.length;i++){
String[] express = content[i].trim().split("=");
if(content[i].contains("=") && express.length <= 2){
if("a".equals(express[0])){
if(express.length == 1){
a = "";
}else{
a = express[1];
}
}else if("b".equals(express[0])){
if(express.length == 1){
b = "";
}else{
b = express[1];
}
}else if("c".equals(express[0])){
if(express.length == 1){
c = "";
}else{
c = express[1];
}
}else if("d".equals(express[0])){
if(express.length == 1){
d = "";
}else{
d = express[1];
}
}else if("e".equals(express[0])){
if(express.length == 1){
e = "";
}else{
e = express[1];
}
}else if("f".equals(express[0])){
if(express.length == 1){
f = "";
}else{
f = express[1];
}
}
}
  }

------解决方案--------------------
Java code

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Message {
    public static void main(String args[]){
        String string="a=0|b=xxx|c=xxx|d=|e=|f=xxx";
        HashMap<String,String> map =new HashMap<String,String>();
        String[] temp = new String[2];
        Pattern p = Pattern.compile("([^\\|]*)=([^\\|]*)");
        Matcher m = p.matcher(string);
        while(m.find()){
            temp[0]=m.group(1);
            temp[1]=m.group(2);
System.out.println(temp[0]+"="+temp[1]);
            map.put(temp[0], temp[1]);
        }

    System.out.println(map);
    }
}
//运行结果
a=0
b=xxx
c=xxx
d=
e=
f=xxx
{f=xxx, d=, e=, b=xxx, c=xxx, a=0}