使用正则表达式获得最佳组匹配

Get Best Group Match Using Regex

我有一个语法字符串,其中定义了组,但我想获得 "best" 可能的匹配。目前它只是找到第一个有效的匹配项并使用它,但这不是我想要的。我希望它使用更匹配它的匹配项。 这就是我所拥有的:

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;
    }

}

这让我明白了:

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}]

但我想得到:

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}]

我能做些什么来改变这个?

终于解决了

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

告诉我这是如何工作的。

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