Preston159
Preston159

Reputation: 302

How can I parse from a line of text in Java?

I have a Java program in which a line of text is received which is similar to the following

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

The text is received from a Teamspeak query, and always has the same number of arguments. I need to parse it in a way with which I can receive the value of clid by knowing the value of client_nickname, for example, with something like clid.get("Alessandro") to receive 1, and clid.get("Braden") to receive 2, possibly with a HashMap<String, Integer>.

Is there a simple way to parse data in that format?

Upvotes: 0

Views: 134

Answers (3)

fipple
fipple

Reputation: 360

Another similar solution:

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"));
}

Upvotes: 0

Tesseract
Tesseract

Reputation: 8139

You could also do it like this.

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"));
}

Upvotes: 1

aliteralmind
aliteralmind

Reputation: 20163

Here is a Java application that parses each user. I've created a UserData class to both parse and store the data, which makes the main function as concise as possible. It also reuses the matcher object, to avoid creating new patterns and objects for each user. Sort of pointless in this demo containing only two users, but invaluable when there is lots of input.

   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;
   }
}

Main function:

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());
      }
   }
}

Output:

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

Full source:

   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;
   }
}

Upvotes: 0

Related Questions