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

时间:2016-01-29 20:59:22

标签: java regex pattern-matching regex-group

我有一个语法字符串,其中定义了组,但我想获得“最佳”匹配。目前它只找到第一个有效并使用它的匹配,但这不是我想要的。我希望它能够使用与之匹配的匹配。 这就是我所拥有的:

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:[随机5到6,null,null,变量]
  Test2:[5/3,null,null,variable]
  测试3:[在线玩家随机0,无效,无效,变量]
  测试4:[玩家手,null,null,{mugs}]
  测试5:[成员添加,null,null,{total members}]

但我想得到:

  

测试1:[null,5,6,变量]
  Test2:[5/3,null,null,variable]
  测试3:[null,0,在线玩家,变量]
  测试4:[玩家手,null,null,{mugs}]
  测试5:[成员添加,null,null,{total members}]

我该怎么做才能改变这个?

1 个答案:

答案 0 :(得分:1)

终于解决了它。

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

告诉我这是如何运作的。

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