1 package io.jawk.jrt;
2
3 /*-
4 * ╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲
5 * Jawk
6 * ჻჻჻჻჻჻
7 * Copyright (C) 2006 - 2026 MetricsHub
8 * ჻჻჻჻჻჻
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Lesser General Public License as
11 * published by the Free Software Foundation, either version 3 of the
12 * License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Lesser Public License for more details.
18 *
19 * You should have received a copy of the GNU General Lesser Public
20 * License along with this program. If not, see
21 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
22 * ╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱
23 */
24
25 import java.util.Enumeration;
26 import java.util.regex.Pattern;
27
28 /**
29 * Similar to StringTokenizer, except that tokens are delimited
30 * by a regular expression.
31 *
32 * @author Danny Daglas
33 */
34 public class RegexTokenizer implements Enumeration<Object> {
35
36 private String[] array;
37 private int idx = 0;
38
39 /**
40 * Construct a RegexTokenizer.
41 *
42 * @param input The input string to tokenize.
43 * @param delimitterRegexPattern The regular expression delineating tokens
44 * within the input string.
45 */
46 public RegexTokenizer(String input, String delimitterRegexPattern) {
47 this(input, delimitterRegexPattern, 0);
48 }
49
50 /**
51 * Construct a RegexTokenizer with explicit {@link Pattern} flags.
52 *
53 * @param input The input string to tokenize.
54 * @param delimitterRegexPattern The regular expression delineating tokens
55 * within the input string.
56 * @param flags {@link Pattern} compilation flags, such as
57 * {@link Pattern#CASE_INSENSITIVE}
58 */
59 public RegexTokenizer(String input, String delimitterRegexPattern, int flags) {
60 this(input, Pattern.compile(delimitterRegexPattern, flags));
61 }
62
63 /**
64 * Construct a RegexTokenizer around a precompiled pattern.
65 *
66 * @param input The input string to tokenize.
67 * @param pattern The compiled delimiter pattern.
68 */
69 public RegexTokenizer(String input, Pattern pattern) {
70 if (input.isEmpty()) {
71 array = new String[0];
72 } else {
73 array = pattern.split(input, -1);
74 }
75 }
76
77 /** {@inheritDoc} */
78 @Override
79 public boolean hasMoreElements() {
80 return idx < array.length;
81 }
82
83 /** {@inheritDoc} */
84 @Override
85 public Object nextElement() {
86 return array[idx++];
87 }
88 }