Reputation: 195
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.
Upvotes: 1
Views: 2261
Reputation: 200148
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);
}
Upvotes: 1
Reputation: 122364
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.
}
Upvotes: 0
Reputation: 11482
Try not to create one big expression but various small ones. E.g the expression to match the -p part would be: -p ?(.*?)
(untested).
Upvotes: 0
Reputation: 5207
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?
Upvotes: 2
Reputation: 13450
use this regex -(\w) ([\w!@#$%^&*():\\/.]+)
group[1]
contain flag, group[2]
contain argument
Upvotes: 2
Reputation: 9260
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 :)
Upvotes: 1