1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5. public class DryRunMatcher {
  6. public static Map<String, Boolean> matchOptions(String commandLine) {
  7. Map<String, Boolean> options = new HashMap<>();
  8. // Define patterns for each option. Case-insensitive.
  9. Pattern dryRunPattern = Pattern.compile("^-d\\s+(.*)$", Pattern.CASE_INSENSITIVE); // -d
  10. Pattern verbosePattern = Pattern.compile("^-v\\s+(.*)$", Pattern.CASE_INSENSITIVE); // -v
  11. Pattern quietPattern = Pattern.compile("^-q\\s+(.*)$", Pattern.CASE_INSENSITIVE); // -q
  12. Pattern helpPattern = Pattern.compile("^-h\\s+(.*)$", Pattern.CASE_INSENSITIVE); // -h
  13. // Check for dry-run option
  14. Matcher dryRunMatcher = dryRunPattern.matcher(commandLine);
  15. if (dryRunMatcher.find()) {
  16. options.put("dryRun", true);
  17. }
  18. // Check for verbose option
  19. Matcher verboseMatcher = verbosePattern.matcher(commandLine);
  20. if (verboseMatcher.find()) {
  21. options.put("verbose", true);
  22. }
  23. // Check for quiet option
  24. Matcher quietMatcher = quietPattern.matcher(commandLine);
  25. if (quietMatcher.find()) {
  26. options.put("quiet", true);
  27. }
  28. // Check for help option
  29. Matcher helpMatcher = helpPattern.matcher(commandLine);
  30. if (helpMatcher.find()) {
  31. options.put("help", true);
  32. }
  33. return options;
  34. }
  35. public static void main(String[] args) {
  36. String commandLine1 = "-d --some-other-option";
  37. String commandLine2 = "-v -q";
  38. String commandLine3 = "-h";
  39. String commandLine4 = "some command";
  40. String commandLine5 = "-D --dry-run"; //Test case insensitivity
  41. System.out.println("Command Line 1: " + commandLine1 + " -> " + matchOptions(commandLine1));
  42. System.out.println("Command Line 2: " + commandLine2 + " -> " + matchOptions(commandLine2));
  43. System.out.println("Command Line 3: " + commandLine3 + " -> " + matchOptions(commandLine3));
  44. System.out.println("Command Line 4: " + commandLine4 + " -> " + matchOptions(commandLine4));
  45. System.out.println("Command Line 5: " + commandLine5 + " -> " + matchOptions(commandLine5));
  46. }
  47. }

Add your comment