Search code examples
javaregexarrayliststring-parsing

Empty element inserted into ArrayList when reading from command line


I have code that i'm running to get a list of user groups from the command line of a given user, using the following code:

private ArrayList<String> accessGroups = new ArrayList<String>();

public void setAccessGroups(String userName) {
    try {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("/* code to get users */");

        BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

        String line = null;

        // This code needs some work
        while ((line = input.readLine()) != null){  
            System.out.println("#" + line);
            String[] temp;
            temp = line.split("\\s+");
            if(line.contains("GRPNAME-")) { 
                for(int i = 0; i < temp.length; i++){
                    accessGroups.add(temp[i]);
                }
            }
        }
        // For debugging purposes, to delete
        System.out.println(accessGroups);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

The code to get users returns a result containing the following:

#Local Group Memberships      *localgroup1          *localgroup2      
#Global Group memberships     *group1               *group2    
#                             *group3               *group4       
#                             *GRPNAME-1            *GRPNAME-2             

The code is designed to extract anything beginning with GRPNAME-. This works fine, it's just if I print the ArrayList I get:

[, *GRPNAME-1, *GRPNAME-2]

There's an reference to a string of "". Is there a simple way I can alter the regex, or another solution I could try to remove this from occurring at the point of being added.

The expected output is:

[*GRPNAME-1, *GRPNAME-2]

Edit: answered, edited output to reflect changes in code.


Solution

  • Instead of this tokenization as presented from this snippet:

    line.split("\\s+");
    

    Use a pattern to match \S+ and add them to your collection. For example:

    // Class level
    private static final Pattern TOKEN = Pattern.compile("\\S+");
    
    // Instance level
    {
        Matcher tokens = TOKEN.matcher(line);
        while (tokens.find())
            accessGroups.add(tokens.group());
    }