Reputation: 88
I have a simple Java application that's a GUI for a command line application, and I have a field where the user can add additional command line arguments. The thing is, I want to pass all arguments to an "option file" the CLI application uses, but to do that I need to split each argument accordingly.
An example:
--edit info --set title=My Title 1 --edit track:v1 --set flag-default=0 --set flag-forced=0
Must become
--edit
info
--set
title=My Title 1
--edit
track:v1
--set
flag-default=1
--set
flag-forced=0
I basically need a RegEx that will match this: --set[MATCH]title=My Title 1[MATCH]--edit[MATCH]track:v1
I don't know if this is simple or not, I tried several RegEx arguments but it was way over my head.
The CLI application is mkvpropedit, by the way.
Upvotes: 2
Views: 4458
Reputation: 1
I had the same problem. I couldn't really split on the argument as a delimiter because then I wouldn't know what each argument was. I ended up doing it this way:
/**
* This method takes the command line arguments and turns them back into a single string.
* Then it looks for argument identifiers and values. In my case the arguments were
* like --action (or the synonym -a), --properties (or -p), etc.
*
* I only needed the first letter of the argument for my purposes but you can adjust
* the regex pattern to return more of group(1) if you need it.
*
* @param args
*/
private HashMap<String,String> parseArguments(String[] args){
HashMap<String,String> rawArguments = new HashMap<String,String>();
String input = new String();
for(int i=0;i<args.length;i++){
input+=args[i]+" ";
}
Pattern pattern = Pattern.compile("-?-([A-z])[A-z]* (.*?)");
Matcher matcher = pattern.matcher(input);
String key=null;
String val=null;
int re=0;
int st=0;
while(matcher.find()){
st=matcher.start();
if(key!=null){
val=input.substring(re, st).trim();
rawArguments.put(key,val);
}
key=matcher.group(1);
if(!matcher.hitEnd()){
re=matcher.end();
}
}
val=input.substring(re).trim();
rawArguments.put(key,val);
return rawArguments;
}
Upvotes: 0
Reputation: 17444
I don't see why you need a regexp here...
In case you're not constrained by some requirement that I don't understand I really think that to parse GNU style command line options you need to use GNU utility getopt
, its Java version in particular.
If you're using Maven using it boils down to adding this to your pom:
<dependency>
<groupId>gnu.getopt</groupId>
<artifactId>java-getopt</artifactId>
<version>1.0.13</version>
</dependency>
Upvotes: 3
Reputation: 8598
If it is not restricted to regex then you may find this command line argument parsing useful to achieve what you want. It provides better ways than regex to do this stuff.
Upvotes: 2
Reputation: 115328
As far as I understand you just have to split string using space as a separator. In this case do the following: str.split("\\s+")
.
Upvotes: -3