1

I'm absolutely not familiar with regexes so better to ask then do something very silly. I have a java application that is to be executed from command line, and it has a pretty nice signature.

java applicationName -mode=create -some.nice.arg=XXX.XXX.XXX.XXX:XXXX -another.nice.arg=value2 -third.nice.arg=value3 -again.nice.arg=value4 ... -nth.nice.arg=value_n+1

This would be the desired format. Well at least close enough. I'm trying to create a regexp that matches this and would select the argument fields like:

  • mode=create
  • some.nice.arg=XXX.XXX.XXX.XXX:XXXX
  • another.nice.arg=value2
  • third.nice.arg=value3
  • again.nice.arg=value4
  • ...
  • nth.nice.arg=value_n+1

I have no problem creating a regexp for IP address for example, but I can't create one that would match this whole stuff. So far my best bet was:

\w+[ ]{1}\w+[ ]{1}[-]{1}(\w+[=]{1}\w+){+}

Lots of problems. For example \w+ won't match '.' chars but they will be there for sure. Or for another example: mode can have one of the following options:

  • create
  • update
  • clear

I'm kinda shot even at the first problem not to mention the second.

Thanks for every help! - Joey

3 Answers 3

2

The correct way to solve this problem is to use a command line interface library, such as Commons CLI. Using these libraries you can define the arguments for your application and the library will validate the input (i.e. your String[] args) against this.

Most CLI libraries can handle advanced concepts such as optional arguments, flags, multi-part arguments etc. They can also be used to print a helpful usage message for your users. Check out some examples here.

Once you've used a library such as this to gather the arguments, you can then use a regexp (if necessary) to validate each part separately.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome solution. thanks for recommending this Commons CLI. works like a charm.
1

If you really want to create regex for this here is the tip:

mode=(\\w+)\\s+some.nice.arg=((?:\\w{3}\\.){3}\\w{3}:\\w{4})\\s+another.nice.arg=(\\S+?)\\s+third.nice.arg=(\\S+?)\\s+again.nice.arg=(\\S+?)

etc, etc.

However better way is to split you line into segments and then process each one:

String line = ....;
String[] segments = line.split("\\s+");

for (String segment : segments) {
    String[] parts = segment.split("=");
    String name = parts[0];
    String value = name[1];
    // deal with names and values
}

Comments

0

This could suit your needs to capture the parameters:

-([a-zA-Z.-]+)=((?:"[^"]+"|[^ ])+)

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.