0

I am currently working on a multiplayer based game. The chat is not only supposed to be there for conversation, but is also supposed to act like a server command line.

If the parser receives a chat input contain certain key words, it is supposed to treat it like a command, f.e.:

Hallo!

- should not trigger anything special

kick SomePlayer
tell Hey people, welcome to our server!
someotherCommand followed by multiple arguments

- they all are supposed to be caught by the parser

If some command is found (meaning one of they keywords is matched) it is supposed to divide the string following this markup:

A variable "command" is supposed to contain the key word (f.e. kick). An array "args" is supposed to contain all following words divided by a white space.

I know, I should be using regex for that, however, I am a little bit stuck on this problem. Can anyone help me?

MrR
  • 171
  • 5

2 Answers2

0

In general, try not to use regexps for parsing. See http://kore-nordmann.de/blog/do_NOT_parse_using_regexp.html and Building a Regex Based Parser.

That said, prepending commands with a special character would avoid a few headaches ("/kick SomePlayer"). Otherwise you need to parse the input into tokens (separated by whitespace, presumably) and check if the first token is a keyword ("kick"). If you want a regexp for this it's something like

([^\s]+) (.*)

(assuming your regexp engine recognizes "\s"; if not you can use " " or " \t" inside the square brackets, after the '^'). This will capture the first word in the group 1 and the rest in group 2 (group 0 would be the full match, here the full line probably).

Note that capturing a variable amount of groups (your list of arguments) may be tricky. See Regular expression with variable number of groups?

Community
  • 1
  • 1
ctn
  • 2,797
  • 10
  • 23
0

I think you can use regular expression (tell|kick)?\s+([^\s]+)*

If you are using Java, following code works. (first match group you have to split as it will contain the command and first arg)

     Pattern patter=Pattern.compile("(tell|kick)?\\s+([^\\s]+)*");

      Matcher matcher=patter.matcher(s);
      while(matcher.find())
      {
          System.out.println(matcher.group());
      }

INPUT: tell hello there! are you ready

OUTPUT:

  tell hello 
  there!
  are
  you
  ready

Hope this helps!

prashantsunkari
  • 939
  • 7
  • 21