0

I have a doubt with a problem that I have to resolve in Java. The thing is: my program receives two arguments by console, the first one is the file's path where I have to load this file to the java program, It's a .ini file. The second argument is a code, with this pattern: XXX-XXXX or XXX-XXXX-XXXX where 'X' are numbers from 0 to 9. Here in the second argument my problem comes in: I have to use the packet java.util.regex to implement this pattern, I mean, I have to validate that the user input the arguments properly. How can I do this? The part of my code that implements this is the following, thanks in advance:

Pattern patron = Pattern.compile("^[0-9]{3,}"); //aqui va la regex que queremos poner
    Matcher match = patron1.matcher(args[1]);


    if(args.length < 2){ // el programa espera recibir dos argumentos

        System.out.println("ERROR, número de argumentos inválido!");
        System.exit(1); //termina el programa
    } else if(args[0].endsWith("config.ini") == false){ //COMPLETAR la segunda condicion
        System.out.println("ERROR, los argumentos no toman valores válidos");
        System.exit(1);
    }

1 Answer 1

1

You can use something like this:

if(args.length >= 2 && args[1] != null && args[1].matches("^\\d{3,}(\\-\\d{3,}){1,2}$"))

^ stands for start of the string

\\d{3,} a number repeating 3 or more times

(\\-\\d{3,}) a group composed of a dash and the construct explained above

{1,2} means that group repeating between one and two times

$ the end of the string

Sign up to request clarification or add additional context in comments.

4 Comments

Please, would you explain me a little bit the regex that you used? Thanks a lot
@user71209 I've edited my answer to try to explain the regex. You can find a better explanation HERE
much better! The only doubt is why do you put a double backslash, it is because we are in Java? I mean, in the page regex101 its only neccessary one backslash, for instance: \d{3} --> a three digit number
@user71209 Yes, other languages have regex literals and you can use only one slash but in Java, because we're using String literals, we have to escape the slash.

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.