1
String regex = "^-admin -s ([^\\s]+) -port (\\d{4}) -u ([^\\s]+) -konf +([^\\s]+.xml)( -pause)?( -start)?( -stop)?( -save)?( -clean)?( -stat)?( -upload [^ ]+)?( -download [^ ]+)?$";

I need to catch the parameters when my program starts. The initial parameters are required but I have one optional parameter that if provided needs to be one from a specific list.

I use the groups I put the parameters in to check if the optional parameter exists, and if there is only one. If so, I use the name of that parameter to call the associated command. Basically I count the groups that are after the -konf parameter (and xml filename) and if there is more than one parameter I write an error message.

Can I use only regex to make the last parameter optional, and only one from a list? For example, the user should be able to write any one of these parameters:

-pause
-start
-stop
-save
-clean
-stat
-upload datoteka
-download datoteka

Examples:

// pass
-admin -s localhost -port 8000 -u username -konf file.xml -pause
-admin -s localhost -port 8000 -u username -konf file.xml -save
-admin -s localhost -port 8000 -u username -konf file.xml -upload datoteka

These should pass, but the next examples should not because there is more than one command after the -konf parameter.

// fail
-admin -s localhost -port 8000 -u username -konf file.xml -pause -save
-admin -s localhost -port 8000 -u username -konf file.xml -pause -clean
bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37
InsaneCricket
  • 125
  • 2
  • 13

1 Answers1

3

Here is a regular expression that matches zero or one option from a set of options:

( -(pause|start|download [^ ]+))?

Matches either:

-pause
-start
-download filename
// or nothing

But not:

-pause -start
-delete
-download
-download file name with space

Explanation:

Text separated by the pipe symbol | within parenthesis () makes each group between pipes an optional match. For example: (a|b|c) can be read: match letter "a" or "b" or "c". ("ab" and "d" do not match.)

A question mark ? makes what comes before it optional. If the character immediately before is something other than a close paren ) then the question mark makes only that character optional. ab? can be read: match letter "a" by itself, or match an "a" followed by letter "b". ("ac" does not match.)

If the question mark ? is preceded by a close paren ), then the question mark makes everything between the close paren and it's matching open paren ( optional. a(bc)? can be read: match letter a by itself, or match an "a" followed by letter "b" and "c". ("ab" and "ac" and "abd" do not match.)

So we're putting those together: ((a|b|c))? can be read match letter "a" or "b" or "c" or nothing at all.

bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37