topper1309 topper1309 - 25 days ago 6
Java Question

Using regex to remove comma and whitespaces and divide them in different variables

Is there any efficient way of doing this?

I want to pass the arg to command line and divide them to following:


  1. String[] command

  2. String[] word

  3. String[] fileName



Example:

String[] arg = {"-b", "-f", "-i", "Dog", "Cat", "--", "fileName1.txt", "fileName2.txt", "fileName3.txt"};
Main.main(arg);

String[] arg = {"-f", "-i", "Hi", "Hello", "--", "fileName1.txt", "fileName2.txt"};
Main.main(arg);

String[] arg = {"-i", "Hi", "Hello", "--", "fileName2.txt"};
Main.main(arg);


NOTE:

Syntax: "[-b] [-f] [-l] [-i] <from> <to> -- " + "fileName"


In syntax - command, word -- fileName

"--" it will be in between and file name everytime.

I have done the following code which is not efficient. Using String.split(" ") and dividing again and again to different arrays of string which is not efficient.

Answer

I never understand the desire to use regexes for simple things like this. Why not just create three lists and loop over the arguments while splitting them into the right list?

ArrayList<String> flags = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
ArrayList<String> files = new ArrayList<>();
for (String arg : args) {
    if (arg.equals("--")) {
        continue;
    }
    if (arg.contains(".")) {
        files.add(arg);
    }else if (arg.contains("-")) {
        flags.add(arg);
    }else {
        words.add(arg);
    }
}

Once you have all the arguments split up by type you can easily do whatever you want with them or rearrange them as you wish. This is more efficient than a regex as well.