I have a problem with parsing message. I created UDP/IP chat and my server is recognizing if message is a command or a message to send to other clients.
Below method checks if data that came matches my regex:
public int isUsernameInitFrame(DatagramPacket dp) {
String command = new String(dp.getData());
Pattern p = Pattern.compile("\\$init:([A-Za-z][A-Za-z0-9]*)");
Matcher m = p.matcher(command);
String username = "";
if (m.matches()) {
while (m.find()) {
username = m.group(1);
}
if (!clients.containsKey(username)) {
clients.put(username, new ClientData(dp.getPort(), dp.getAddress()));
System.out.println("Client has been added");
return 2;
} else {
System.out.println("Client cannot be added");
return 0;
}
} else {
return 1;
}
}
Command I send to add user is $init:<username>
so my regex should work as I checked it here and also this code belowe prints asd
as well.
String test = "$init:asd";
if(test.matches("\\$init:([A-Za-z][A-Za-z0-9]*)")){
System.out.println("working!");
}
But my method always do return 1
, so it doesn't match (?). I noticed that when I print my message as byte array it looks like
36 105 110 105 116 58 97 115 100 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
and after I do new String(dp.getData())
it's $init:asd
on console but when I copy it there is a lot blank characters and I don't know how to get rid of them. And those are not even space character in byte value. Maybe it does not even matter in this case. So why it's not working?