aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/de/hysky/skyblocker/utils/container/RegexContainerMatcher.java
blob: 4df0fe1a99e0a314f03db6ab31d7e897b9249135 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package de.hysky.skyblocker.utils.container;

import de.hysky.skyblocker.skyblock.ChestValue;
import net.minecraft.client.gui.screen.ingame.HandledScreen;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

/**
 * A regex implementation of {@link ContainerMatcher} that matches the title of the screen.
 */
public abstract class RegexContainerMatcher implements ContainerMatcher {
	/**
	 * The title of the screen must match this pattern for this to be applied. Null means it will be applied to all screens.
	 *
	 * @implNote Don't end your regex with a {@code $} as {@link ChestValue} appends text to the end of the title,
	 * so the regex will stop matching if the player uses chest value.
	 */
	@Nullable
	public final Pattern titlePattern;

	@Nullable
	public String[] groups = null;

	@Override
	public boolean test(@NotNull HandledScreen<?> screen) {
		return test(screen.getTitle().getString());
	}

	public boolean test(@NotNull String title) {
		if (titlePattern == null) return true;
		Matcher matcher = titlePattern.matcher(title);
		if (matcher.matches()) {
			int groupCount = matcher.groupCount();
			if (groupCount >= 1) { //No need to initialize the array if there are no groups
				groups = new String[groupCount];
				for (int i = 0; i < groupCount; i++) {
					groups[i] = matcher.group(i + 1); // +1 because first group is the whole match, which is useless
				}
			}
			return true;
		}
		return false;
	}

	protected RegexContainerMatcher() {
		this((Pattern) null);
	}

	protected RegexContainerMatcher(@NotNull @Language("RegExp") String titlePattern) {
		this(Pattern.compile(titlePattern));
	}

	protected RegexContainerMatcher(@Nullable Pattern titlePattern) {
		this.titlePattern = titlePattern;
	}

	public @Nullable Pattern getTitlePattern() {
		return titlePattern;
	}

	public final @Nullable String[] getGroups() {
		return groups;
	}
}