have a such issue with regexp in java. I code chat application and client could sent to the server just “message” or “\command value”. I want to parse this string and check was a command i the line or not. If it login – value is required, but if it logout value.required should be false. I create such regexp
"^\\\\(?<comm>login|status|((?=logout)))\\s(?<content>\\w+)"
What should i write to logout condition? I want to have logout in comm group. I should write
something like if logout than do not read anything else which steps after.
I would probably do the checking for whether a certain command should have a parameter or not in general purpose code (i.e. Java) rather than in the regular expression. That is to say, Regular Expressions are good for tokenizing, but not so much for parsing.
However, if you’ve got a good reason to do it that way, then I would probably split the expression into two parts – one where the commands require a command, and one where they do not. For example:
Note that the final
(?<param>)is not strictly necessary for the regular expression to operate correctly, it is merely there so that any subsequent code can rely on two named groups in the result: command and param.Logically, this could be extended to three groups where the third group contains commands with an optional parameter.
This can more clearly be written like so if you’re using Groovy (or Java 7) for multi-line strings: