javaregexregex-group

Get Best Group Match Using Regex


I have a syntax string that has groups defined in it, but I want to get the "best" match possible. Currently it just finds the first match that works and uses it, but thats not what I want. I want it to use the match that matches it even more. This is what I have:

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("add ((?<n0>.*)|random (?<n1>.*) to (?<n2>.*)) to (?<n3>.*)");
        String test1 = "add random 5 to 6 to variable";
        String test2 = "add 5 / 3 to variable";
        String test3 = "add random 0 to players online to variable";
        String test4 = "add player hand to {mugs}";
        String test5 = "add members added to {total members}";
        String[] groups1 = extractGroups(pattern, test1, 4);
        String[] groups2 = extractGroups(pattern, test2, 4);
        String[] groups3 = extractGroups(pattern, test3, 4);
        String[] groups4 = extractGroups(pattern, test4, 4);
        String[] groups5 = extractGroups(pattern, test5, 4);
        System.out.println(Arrays.toString(groups1));
        System.out.println(Arrays.toString(groups2));
        System.out.println(Arrays.toString(groups3));
        System.out.println(Arrays.toString(groups4));
        System.out.println(Arrays.toString(groups5));
    }

    private static String[] extractGroups(Pattern pattern, String string, int groups) {
        String[] groupList = new String[groups];
        Matcher matcher = pattern.matcher(string);
        if (matcher.find()) {
            for (int i = 0; i < groups; i++) {
                String groupName = "n" + i;
                groupList[i] = matcher.group(groupName);
            }
        }
        return groupList;
    }

}

This gets me:

Test1: [random 5 to 6, null, null, variable]
Test2: [5 / 3, null, null, variable]
Test3: [random 0 to players online, null, null, variable]
Test4: [player hand, null, null, {mugs}]
Test5: [members added, null, null, {total members}]

But I want to get:

Test1: [null, 5, 6, variable]
Test2: [5 / 3, null, null, variable]
Test3: [null, 0, players online, variable]
Test4: [player hand, null, null, {mugs}]
Test5: [members added, null, null, {total members}]

What can I do to change this?


Solution

  • Finally solved it.

    https://regex101.com/r/mM7bV2/3

    Tell me how this works.

    add (?!.*random)(?<n1>.*) to (?<n2>.*)|random (?<n3>.*) to (?<n4>.*) to (?<n5>.*)