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.

kwf2030
  • 195
  • 2
  • 13

6 Answers6

2

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

burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
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?

Community
  • 1
  • 1
xiaowl
  • 5,177
  • 3
  • 27
  • 28
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 :)

nullpotent
  • 9,162
  • 1
  • 31
  • 42
  • I prefer to regex, if the user entered wrong args,like -p -d xxx,the arg[i+1] goes the wrong way. – kwf2030 Jul 31 '12 at 00:53
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);
}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
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).

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
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.
}
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183