Ok in my program (a bot actually), I need to send a message to a certain user name. So right now if I want to send a message to someone with the username "Jack" I type "!send jack:hello there"and the bot sends this message to 'jack' "jack:hello there". The bot does not know that I want anything before ":" to be the username ONLY and anything AFTER : to be the 'message' to send.
So I was told I need to use something like this:
strArguments.split(":", 1);
strArguments is what a user types to the bot. So I need to define TWO DIFFERENT strArguments.
But i'm not sure how to put this into the code.
If !send
is the command to send a message, I prefer to use java.utiil.regex packege to do the. although this may look abit complicated.
public String[] parseSend(String s) {
String p = "\\!send ([a-zA-Z]*)\\:(.*)";
Pattern pattern = Pattern.compile(p);
Matcher matcher = pattern.matcher(s);
String[] result = new String[2];
if (matcher.matches()) {
int start = matcher.start(1);
int end = matcher.end(1);;
result[0] = s.substring(start, end); // name
start = matcher.start(2);
end = matcher.end(2);
result[2] = s.substring(start, end); // msg
}
return result;
}
String[] result = strArguments.split(":", 2);
The second argument to split() is the maximum number of tokens you want returned, i.e., the size of the returned array. If you use '1', the array will have only one element: the whole input string. You effectively told it not to split the string at all.
Mickey, just FYI, instead of getting the indexes and pullling the substrings manually, you can use Matcher's group() methods. public String[] parseSend(String s) {
String p = "!send ([a-zA-Z]*):(.*)";
Pattern pattern = Pattern.compile(p);
Matcher matcher = pattern.matcher(s);
String[] result = new String[2];
if (matcher.matches()) {
result[0] = matcher.group(1)); // name
result[1] = matcher.group(2); // msg
}
return result;
}