如何从Java中的一行文本中解析?

时间:2014-07-16 03:53:45

标签: java parsing

我有一个Java程序,其中收到一行文本,类似于以下

clid=1 cid=2 client_database_id=1 client_nickname=Alessandro client_type=0|clid=2 cid=2 client_database_id=10 client_nickname=Braden client_type=1

文本是从Teamspeak查询中接收的,并且始终具有相同数量的参数。我需要通过知道clid的值来获取client_nickname的值来解析它,例如clid.get("Alessandro")来接收1clid.get("Braden")接收2,可能带有HashMap<String, Integer>

是否有一种简单的方法来解析该格式的数据?

3 个答案:

答案 0 :(得分:1)

你也可以这样做。

static HashMap<String, HashMap<String, String>> extractData(String str) {
  HashMap<String, HashMap<String, String>> data = new HashMap<>();
  for(String s: str.split("\\|")) {
    HashMap<String, String> entries = new HashMap<>();
    for(String s2: s.split(" ")) {
      String[] entry = s2.split("=");
      entries.put(entry[0], entry[1]);
    }
    data.put(entries.get("client_nickname"), entries);
  }
  return data;
}

public static void main(String[] args) {
  String str = "clid=1 cid=2 client_database_id=1 client_nickname=Alessandro client_type=0|clid=2 cid=2 client_database_id=10 client_nickname=Braden client_type=1";

  HashMap<String, HashMap<String, String>> data = extractData(str);
  System.out.println(data.get("Alessandro").get("clid"));
}

答案 1 :(得分:0)

这是一个解析每个用户的Java应用程序。我创建了一个UserData类来解析和存储数据,这使得main函数尽可能简洁。它还重用了matcher对象,以避免为每个用户创建新的模式和对象。在这个只包含两个用户的演示中有点毫无意义,但是当有大量输入时非常有用。

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

class UserData  {

   private static final String REGEX = "clid=([0-9]+) +" +
      "cid=([0-9]+) +" +
      "client_database_id=([0-9]+) +" +
      "client_nickname=(\\w+) +" +
      "client_type=([0-9]+)";
   private static final Matcher mtchrRawDataGroups = Pattern.compile(REGEX).matcher("");

   private final String clid;
   private final String cid;
   private final int clientDbId;
   private final int clientType;  //Guessing this should be an enum
   private final String nickname;

   public UserData(String raw_data)  {
      mtchrRawDataGroups.reset(raw_data);
      if(!mtchrRawDataGroups.matches())  {
         throw  new IllegalArgumentException("raw_data=\"" + raw_data + "\"");
      }

      //All the parse-ints should be try-catched:
      clid = mtchrRawDataGroups.group(1);
      cid = mtchrRawDataGroups.group(2);
      clientDbId = Integer.parseInt(mtchrRawDataGroups.group(3));
      nickname = mtchrRawDataGroups.group(4);
      clientType = Integer.parseInt(mtchrRawDataGroups.group(5));
   }
   public String getClid()  {
      return  clid;
   }
   public String getCid()  {
      return  cid;
   }
   public int getClientDatabaseId()  {
      return  clientDbId;
   }
   public int getClientType()  {
      return  clientType;
   }
   public String getNickname()  {
      return  nickname;
   }
}

主要功能:

public class Test  {
   public static final void main(String[] ignored)  {
      String input = "clid=1 cid=2 client_database_id=1 client_nickname=Alessandro client_type=0|" +
         "clid=2 cid=2 client_database_id=10 client_nickname=Braden client_type=1";

      String[] allUsersData = input.split("\\|");
      for(String userData : allUsersData)  {
         UserData user = new UserData(userData);
         System.out.println("clid=" + user.getClid() + ", nickname=" + user.getNickname());
      }
   }
}

输出:

clid=1, nickname=Alessandro
clid=2, nickname=Braden

完整来源:

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

public class Test  {
   public static final void main(String[] ignored)  {
      String input = "clid=1 cid=2 client_database_id=1 client_nickname=Alessandro client_type=0|" +
         "clid=2 cid=2 client_database_id=10 client_nickname=Braden client_type=1";

      String[] allUsersData = input.split("\\|");
      for(String userData : allUsersData)  {
         UserData user = new UserData(userData);
         System.out.println("clid=" + user.getClid() + ", nickname=" + user.getNickname());
      }
   }
}

class UserData  {
   private static final String REGEX = "clid=([0-9]+) +" +
      "cid=([0-9]+) +" +
      "client_database_id=([0-9]+) +" +
      "client_nickname=(\\w+) +" +
      "client_type=([0-9]+)";
   private static final Matcher mtchrRawDataGroups = Pattern.compile(REGEX).matcher("");

   private final String clid;
   private final String cid;
   private final int clientDbId;
   private final int clientType;  //Guessing this should be an enum
   private final String nickname;
   public UserData(String raw_data)  {
      mtchrRawDataGroups.reset(raw_data);
      if(!mtchrRawDataGroups.matches())  {
         throw  new IllegalArgumentException("raw_data=\"" + raw_data + "\"");
      }

      //All the parse-ints should be try-catched:
      clid = mtchrRawDataGroups.group(1);
      cid = mtchrRawDataGroups.group(2);
      clientDbId = Integer.parseInt(mtchrRawDataGroups.group(3));
      nickname = mtchrRawDataGroups.group(4);
      clientType = Integer.parseInt(mtchrRawDataGroups.group(5));
   }
   public String getClid()  {
      return  clid;
   }
   public String getCid()  {
      return  cid;
   }
   public int getClientDatabaseId()  {
      return  clientDbId;
   }
   public int getClientType()  {
      return  clientType;
   }
   public String getNickname()  {
      return  nickname;
   }
}

答案 2 :(得分:0)

另一个类似的解决方案:

private static final String input = "clid=1 cid=2 client_database_id=1 client_nickname=Alessandro client_type=0|clid=2 cid=2 client_database_id=10 client_nickname=Braden client_type=1";

public static void main(String[] args)
{
    Map<String, Integer> data;
    final Map<String, Map<String, Integer>> records = new HashMap<String, Map<String, Integer>>();

    final String[] chunks = input.split("\\|");
    for (String chunk : chunks)
    {
        data = new HashMap<String, Integer>();
        final String[] items = chunk.split(" ");
        String clientNickName = null;
        for (String nameValue : items)
        {
            String[] fields = nameValue.split("=");
            if ("client_nickname".equals(fields[0]))
            {
                clientNickName = fields[1];
            }
            else
            {
                data.put(fields[0], new Integer(fields[1]));
            }
        }
        records.put(clientNickName, data);
    }
    System.out.println(records.get("Alessandro").get("clid"));
    System.out.println(records.get("Braden").get("clid"));
}