
✂️Command Argument Parser
Define and parse command line arguments
KCmdArgParser Class Overview
Define allowed options and arguments
Parsing of the command line arguments
Methods to query and retrieve options and arguments
Syntax of Parser Definition
- Multiple patterns are separated by colons (e.g. ?-l:?-a)
- 1st character must be be ? for an optional or ! for a required argument
- The following string is either a short or long option (e.g. -x or --xxx) or a specifies a single or multiple argument (. or ..)
- The last character can be set for an optional ? or required option value !
Examples:
- ?-l:?-a:!. Allows optional arguments -l and -a, but requires one single argument
- ?-n?:!.. Allows the optional argument -n (with an optional value, e.g. -n or -n=10) and at least one argument
- ?--header=! Allows an optional long option. If specified, it requires an option value, e.g. --header=yes
- (empty) Empty pattern prohibits any argumentsExample
import ch.k43.util.KCmdArgParser;
public class CmdParser {
public static void main(String[] args) {
// Parser syntax: -a and -l optional, one parameter required
final String ARG_SYNTAX = "?-l:?-a:!.";
// Initialize command line parser with argument syntax
KCmdArgParser argParser = new KCmdArgParser(ARG_SYNTAX);
// Parse command line arguments
if (!argParser.parse(args)) {
System.out.println("Syntax error: " + argParser.getLastError());
System.exit(1);
}
System.out.println("Option -l: " + argParser.hasOption("-l"));
System.out.println("Option -a: " + argParser.hasOption("-a"));
System.out.println("Parameter: " + argParser.getArgument());
}
}Output
Last updated