1

I have cmd like this one:

java Test -p 127.0.0.1:8080 -d D:\Desktop\temp.exe -o mingw -s 1024 -t 2000

I want to get the args with -p,-d or -s(exclude -p,-d,-s itself), and discard other args.

I tried hours but had no result,is there any one can help me?

I tried the arg[i] and arg[i+1] way,but if args like this:-p -d xxx, the user do not enter -p value, this solution will take no effect and cause problems.

1
  • 1
    Give the code you have tried. Why not give a starting point? Commented Jul 30, 2012 at 10:03

6 Answers 6

2

If all your options are in same form -x value, then you can split your args array into groups in form of -d 127.0.0.1:8080, -d D:...

for(int i=0; i < args.length; i+=2){
    //group args
}

for each group in groups:
    if group[0].equals("-d"){
          //do something
    }
}

Or, just have a look at existing OptionParser libraries in Java. How to parse command line arguments in Java?

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

Comments

2

use this regex -(\w) ([\w!@#$%^&*():\\/.]+) group[1] contain flag, group[2] contain argument

2 Comments

could you explain this regex? i can not understand
- litteral symbol, (\w) any digit/letter/_, ([\w!@#$%^&*():\\/.]) any symbol from [], + 1 and more previos symbols
1

How about...

for(int i = 0; i < args.length; i+=2) { 
 if(args[i].equals("-p") {
   //args[i+1] is the value
 } 
 ... 
}

It doesn't use regexes, yay :)

1 Comment

I prefer to regex, if the user entered wrong args,like -p -d xxx,the arg[i+1] goes the wrong way.
1

This solution assembles your args into a map:

public static void main(String[] args) {
  final Map<Character, String> am = new HashMap<Character, String>();
  for (int i = 0; i+1 < args.length; i++)
    if (args[i].matches("-[pds]") && !args[i+1].startsWith("-"))
      am.put(args[i].charAt(1), args[++i]);
  System.out.println(am);
}

2 Comments

if the args entered wrong,like -p -d xxx,no -p value,this would be wrong
...and very easily fixable. Fixed.
0

Try not to create one big expression but various small ones. E.g the expression to match the -p part would be: -p ?(.*?) (untested).

Comments

0

You don't need regular expressions for this, as the arguments come in an array, so you just loop over it:

public static void main(String[] args) {
  Map<String, String> argsMap = new HashMap<String, String>();
  int i = 0;
  while(i < args.length - 1 && args[i].startsWith("-")) {
    argsMap.put(args[i].substring(1), args[++i]);
  }

  System.out.println("-p arg was " + argsMap.get("p"));
  // etc.
}

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.