topper1309 topper1309 - 10 months ago 44
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


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

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

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


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 Source

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("--")) {
    if (arg.contains(".")) {
    }else if (arg.contains("-")) {
    }else {

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.