简体   繁体   中英

Regular expressions, groups issue

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.

You are probably better off making the parameter optional:

^\\(?<command>login|status|logout)(?:\s(?<param>\w+))?

and checking the logic of the results with Java.

If you really want yo use regex, you could do:

^\\(?<command>login|status|logout(?=$))(?:\s(?<param>\w+))?$

I would probably do the checking for whether a certain command should have a parameter or not in general purpose code (ie 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:

^\\(?:(?<command>login)\s+(?<param>\w+)|(?<command>status|logout)(?<param>))$

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:

^\\(?x:
    (?<command>login) \s+ (?<param>\w+)   # Commands that require a parameter
    |                                     # -or-
    (?<command>status|logout) (?<param>)  # Commands that do not require a parameter
)$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM