Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude null regex groups

Tags:

java

regex

Given the following line, I would like to extract some values using Pattern class in Java:

user1@machine1:command#user2@machine2:command....

Two commands are extracted:

  • one to be executed on machine1 using user1
  • one to be executed on machine2 using user2

If I use the following regex

"([^@]+)@([^:]+):([^#]+)(?:#([^@]+)@([^:]+):([^#]+))*"

the elements in group 1, 4, 7, ... are users

the elements in group 2, 5, 8, ... are machines

the elements in group 3, 6, 9, ... are commands

The only problem is that for only one command, the matcher detects null groups for 4, 5, 6.

Is there any Regex option for not receiving null values, for that particular situation?

like image 897
nucandrei Avatar asked Jul 04 '26 08:07

nucandrei


1 Answers

Instead of using one regex for finding all the users, groups, and commands at once, I'd suggest splitting the process in two: First, find blocks of user@group:command, then identify the parts in that block. This way it will work for any number of blocks.

First, trim down your regex to match just one "block":

Pattern p = Pattern.compile("([^@]+)@([^:]+):([^#]+)");
String input = "user1@machine1:command1#user2@machine2:command2#user3@machine3:command3";

Then, either, use String.split("#") to split the blocks and use the regex to match that block:

for (String block : input.split("#")) {
    Matcher m = p.matcher(block);
    if (m.matches()) {
        System.out.println(m.groupCount());
        for (int i = 0; i < m.groupCount(); i++) {
            System.out.println(m.group(i + 1));
        }
    }
}

Or just repeatedly find more matches in the original string:

Matcher m = p.matcher(input);
while (m.find()) {
    System.out.println(m.groupCount());
    for (int i = 0; i < m.groupCount(); i++) {
        System.out.println(m.group(i + 1));
    }
}
like image 110
tobias_k Avatar answered Jul 05 '26 20:07

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!