summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java
blob: 7b4aac032568dcf818cea15edd100329c445af75 (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
package bjc.utils.parserutils.delims;

import bjc.utils.data.IPair;
import bjc.utils.data.Pair;

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

/**
 * A predicated opener for use with {@link RegexOpener}
 * 
 * @author bjculkin
 *
 */
public class RegexOpener implements Function<String, IPair<String, String[]>> {
	private String name;

	private Pattern patt;

	/**
	 * Create a new regex opener.
	 * 
	 * @param groupName
	 *                The name of the opened group.
	 * 
	 * @param groupRegex
	 *                The regex that matches the opener.
	 */
	public RegexOpener(String groupName, String groupRegex) {
		name = groupName;

		patt = Pattern.compile(groupRegex);
	}

	@Override
	public IPair<String, String[]> apply(String str) {
		Matcher m = patt.matcher(str);

		if (m.matches()) {
			int numGroups = m.groupCount();

			String[] parms = new String[numGroups + 1];

			for (int i = 0; i <= numGroups; i++) {
				parms[i] = m.group(i);
			}

			return new Pair<>(name, parms);
		}

		return new Pair<>(null, null);
	}
}