1

I know there is a lot out there.. But I couldn't figure out how to extract two parameters from Scanner(System.in);

commandline = scanner.readLine();

Two parameters are allowed:

First one can be one of AHG or the digits between 4 to 9. The second parameters again between 4 to 9 OR any number. It should handle all the scenarios:

   "      A    3  " //spaces before and after
   "A    3"         // spaces between the params
   "A    7     6"   // Unwanted 3rd parameter
   "  6  "          // Only one param with spaces.

So how to write Regex for this to extract the above? I tried this one. \\w\\s. But this did not work. I am poor with RegEx.

2 Answers 2

3

Use this on the string returned by readLine():

String [] arguments = commandLine.split( "\\s+" );

The \\s+ stands for at least one whitespace character as separator.

Then check how many elements the array has.

Fimally check the formats of the two arguments

  1. arguments[0].matches("\\s*[AHG4-9]");
  2. arguments[1].matches("\\d");
Sign up to request clarification or add additional context in comments.

2 Comments

How do I ignore whitespace and extract only the arguments?
@KevinRave: That's what commandLine.split( "\\s+" ); should do.
2

Try:

public static ArrayList<String> parseArguments(String argument){
    Pattern regex = Pattern.compile("^\\s*([AHG4-9])\\s*(\\d)?\\s*$",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    Matcher regexMatcher = regex.matcher(argument);

    if (regexMatcher.find()) {

        ArrayList<String> arguments = new ArrayList<String>();

        arguments.add(regexMatcher.group(1));

        if(regexMatcher.group(2) != null)
        {
            arguments.add(regexMatcher.group(2));
        }

        return arguments;
    }

    return null;

}

Depending on your input:

It will print:

[A,3]

Above regex also enforce argument rules. e.g as you mention first parameter can be A,H,G or number between 4 and 9. 2nd argument any number and can be optional

6 Comments

I think you are trying to accomplish too much with a single statement. This makes your code difficult to understand.
I'm not sure what do you meant by difficult but tried not only parse arguments but also validate as per OP rules.
The regex you are using is probably hard to understand for most programmers who do not use complex regex regularly. Therefore I prefer to split the input first and then validate the arguments in a second step.
ah, not understanding regex is a totally different story :P
@FrankPuffer How is whitespace; character class; whitespace; optional digit complicated?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.