0

I have a string that represents a command. Each command can be a different length. For example here are some commands

  • showmessage "hello im the message"

  • exit

  • showmessage "im the message" "im the title"

  • playsound /path/to/sound/file

My function takes a string that has the whole command and currently splits the string into a string array using split("\\s+").

However this splits the command at every whitespace. What I need to do is split the command at each space UNLESS something in the command started with " and ends with ". In this case I'd need to split the string so that the string array contains a string that is the whole part of the command that is in quotes.

So if the input command was:

showmessage "the message"

the split string array would contain the strings:

showmessage, "the message"

and if the command was:

showmessage the message

the split array would contain:

showmessage, the, message

Is there a way to do this with regexes?

CS Student
  • 1,613
  • 6
  • 24
  • 40
  • Even if there is a way to do this with Regex, a parser would be the better thing to handle this. Did you consider that showing a message with quotation marks needs escaping of these like `showmessage "message with \"quotes\"" "title"`? – Thomas Weller Sep 07 '15 at 11:12
  • And here is [another answer you can use](http://stackoverflow.com/questions/632475/regex-to-pick-commas-outside-of-quotes). – Wiktor Stribiżew Sep 07 '15 at 11:15
  • There's an old class called [`StreamTokenizer`](http://docs.oracle.com/javase/7/docs/api/java/io/StreamTokenizer.html) that's suitable for parsing simple command languages. Take a look to see if it suits you. – RealSkeptic Sep 07 '15 at 11:17
  • @Thomas I didn't consider the escaping, thanks. – CS Student Sep 07 '15 at 11:28
  • @RealSkeptic I'll check that out, thanks – CS Student Sep 07 '15 at 11:29

0 Answers0