CommandHelpers.java 2.46 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
package emu.grasscutter.command;

import javax.annotation.Nonnull;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommandHelpers {
AnimeGitB's avatar
AnimeGitB committed
11
12
13
    public static final Pattern lvlRegex = Pattern.compile("(?<!\\w)l(?:vl?)?(\\d+)");  // Java doesn't have raw string literals :(
    public static final Pattern amountRegex = Pattern.compile("((?<=(?<!\\w)x)\\d+|\\d+(?=x)(?!x\\d))");
    public static final Pattern refineRegex = Pattern.compile("(?<!\\w)r(\\d+)");
14
    public static final Pattern rankRegex = Pattern.compile("(\\d+)\\*");
AnimeGitB's avatar
AnimeGitB committed
15
    public static final Pattern constellationRegex = Pattern.compile("(?<!\\w)c(\\d+)");
16
    public static final Pattern skillLevelRegex = Pattern.compile("sl(\\d+)");
17
18
19
20
    public static final Pattern stateRegex = Pattern.compile("state(\\d+)");
    public static final Pattern blockRegex = Pattern.compile("blk(\\d+)");
    public static final Pattern groupRegex = Pattern.compile("grp(\\d+)");
    public static final Pattern configRegex = Pattern.compile("cfg(\\d+)");
AnimeGitB's avatar
AnimeGitB committed
21
    public static final Pattern hpRegex = Pattern.compile("(?<!\\w)hp(\\d+)");
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    public static final Pattern maxHPRegex = Pattern.compile("maxhp(\\d+)");
    public static final Pattern atkRegex = Pattern.compile("atk(\\d+)");
    public static final Pattern defRegex = Pattern.compile("def(\\d+)");
    public static final Pattern aiRegex = Pattern.compile("ai(\\d+)");

    public static int matchIntOrNeg(Pattern pattern, String arg) {
        Matcher match = pattern.matcher(arg);
        if (match.find()) {
            return Integer.parseInt(match.group(1));  // This should be exception-safe as only \d+ can be passed to it (i.e. non-empty string of pure digits)
        }
        return -1;
    }

    public static <T> List<String> parseIntParameters(List<String> args, @Nonnull T params, Map<Pattern, BiConsumer<T, Integer>> map) {
        for (int i = args.size() - 1; i >= 0; i--) {
            String arg = args.get(i).toLowerCase();
            boolean deleteArg = false;
            int argNum;
            for (var entry : map.entrySet()) {
                if ((argNum = matchIntOrNeg(entry.getKey(), arg)) != -1) {
                    entry.getValue().accept(params, argNum);
                    deleteArg = true;
                    break;
                }
            }
            if (deleteArg) {
                args.remove(i);
            }
        }
        return args;
    }
}