Debian Codegraph @

net/sf/saxon/regex/JRegexIterator.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.regex;
9
10 import net.sf.saxon.expr.LastPositionFinder;
11 import net.sf.saxon.functions.Count;
12 import net.sf.saxon.trans.XPathException;
13 import net.sf.saxon.tree.util.FastStringBuffer;
14 import net.sf.saxon.value.StringValue;
15 import net.sf.saxon.z.IntHashMap;
16 import net.sf.saxon.z.IntToIntHashMap;
17
18 import java.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23 //import java.util.regex.Matcher;
24 //import java.util.regex.Pattern;
25
26 /**
27 * Class JRegexIterator - provides an iterator over matched and unmatched substrings.
28 * This implementation of RegexIterator uses the JDK regular expression engine.
29 */
30
31 public class JRegexIterator implements RegexIterator, LastPositionFinder {
32
33 private String theString; // the input string being matched
34 private Pattern pattern; // the regex against which the string is matched
35 private Matcher matcher; // the Matcher object that does the matching, and holds the state
36 /*@Nullable*/ private String current; // the string most recently returned by the iterator
37 private String next; // if the last string was a matching string, null; otherwise the next substring
38 // matched by the regex
39 private int prevEnd = 0; // the position in the input string of the end of the last match or non-match
40 private IntToIntHashMap nestingTable = null;
41 // evaluated on demand: a table that indicates for each captured group,
42 // what its immediately-containing captured group is.
43
44 /**
45 * Construct a RegexIterator. Note that the underlying matcher.find() method is called once
46 * to obtain each matching substring. But the iterator also returns non-matching substrings
47 * if these appear between the matching substrings.
48 *
49 * @param string the string to be analysed
50 * @param pattern the regular expression
51 */
52
53 public JRegexIterator(String string, Pattern pattern) {
54 theString = string;
55 this.pattern = pattern;
56 matcher = pattern.matcher(string);
57 next = null;
58 }
59
60 @Override
61 public int getLength() throws XPathException {
62 JRegexIterator another = new JRegexIterator(theString, pattern);
63 return Count.steppingCount(another);
64 }
65
66
67 /**
68 * Get the next item in the sequence
69 *
70 * @return the next item in the sequence
71 */
72
73 public StringValue next() {
74 if (next == null && prevEnd >= 0) {
75 // we've returned a match (or we're at the start), so find the next match
76 if (matcher.find()) {
77 int start = matcher.start();
78 int end = matcher.end();
79 if (prevEnd == start) {
80 // there's no intervening non-matching string to return
81 next = null;
82 current = theString.substring(start, end);
83 prevEnd = end;
84 } else {
85 // return the non-matching substring first
86 current = theString.substring(prevEnd, start);
87 next = theString.substring(start, end);
88 }
89 } else {
90 // there are no more regex matches, we must return the final non-matching text if any
91 if (prevEnd < theString.length()) {
92 current = theString.substring(prevEnd);
93 next = null;
94 } else {
95 // this really is the end...
96 current = null;
97 prevEnd = -1;
98 return null;
99 }
100 prevEnd = -1;
101 }
102 } else {
103 // we've returned a non-match, so now return the match that follows it, if there is one
104 if (prevEnd >= 0) {
105 current = next;
106 next = null;
107 prevEnd = matcher.end();
108 } else {
109 current = null;
110 return null;
111 }
112 }
113 return StringValue.makeStringValue(current);
114 }
115
116 /**
117 * Get properties of this iterator, as a bit-significant integer.
118 *
119 * @return the properties of this iterator. This will be some combination of
120 * properties such as {@link #GROUNDED}, {@link #LAST_POSITION_FINDER},
121 * and {@link #LOOKAHEAD}. It is always
122 * acceptable to return the value zero, indicating that there are no known special properties.
123 * It is acceptable for the properties of the iterator to change depending on its state.
124 */
125
126 public int getProperties() {
127 return LAST_POSITION_FINDER;
128 }
129
130 /**
131 * Determine whether the current item is a matching item or a non-matching item
132 *
133 * @return true if the current item (the one most recently returned by next()) is
134 * an item that matches the regular expression, or false if it is an item that
135 * does not match
136 */
137
138 public boolean isMatching() {
139 return next == null && prevEnd >= 0;
140 }
141
142 /**
143 * Get a substring that matches a parenthesised group within the regular expression
144 *
145 * @param number the number of the group to be obtained
146 * @return the substring of the current item that matches the n'th parenthesized group
147 * within the regular expression
148 */
149
150 public String getRegexGroup(int number) {
151 if (!isMatching()) return null;
152 if (number > matcher.groupCount() || number < 0) return "";
153 String s = matcher.group(number);
154 if (s == null) return "";
155 return s;
156 }
157
158 /**
159 * Get the number of captured groups
160 */
161 public int getNumberOfGroups() {
162 return matcher.groupCount();
163 }
164
165 /**
166 * Process a matching substring, performing specified actions at the start and end of each captured
167 * subgroup. This method will always be called when operating in "push" mode; it writes its
168 * result to context.getReceiver(). The matching substring text is all written to the receiver,
169 * interspersed with calls to the methods onGroupStart() and onGroupEnd().
170 *
171 * @param action defines the processing to be performed at the start and end of a group
172 */
173
174 public void processMatchingSubstring(MatchHandler action) throws XPathException {
175 int c = matcher.groupCount();
176 if (c == 0) {
177 action.characters(current);
178 } else {
179 // Create a map from positions in the string to lists of actions.
180 // The "actions" in each list are: +N: start group N; -N: end group N.
181 IntHashMap<List<Integer>> actions = new IntHashMap<List<Integer>>(c);
182 for (int i = 1; i <= c; i++) {
183 int start = matcher.start(i) - matcher.start();
184 if (start != -1) {
185 int end = matcher.end(i) - matcher.start();
186 if (start < end) {
187 // Add the start action after all other actions on the list for the same position
188 List<Integer> s = actions.get(start);
189 if (s == null) {
190 s = new ArrayList<Integer>(4);
191 actions.put(start, s);
192 }
193 s.add(i);
194 // Add the end action before all other actions on the list for the same position
195 List<Integer> e = actions.get(end);
196 if (e == null) {
197 e = new ArrayList<Integer>(4);
198 actions.put(end, e);
199 }
200 e.add(0, -i);
201 } else {
202 // zero-length group (start==end). The problem here is that the information available
203 // from Java isn't sufficient to determine the nesting of groups: match("a", "(a(b?))")
204 // and match("a", "(a)(b?)") will both give the same result for group 2 (start=1, end=1).
205 // So we need to go back to the original regex to determine the group nesting
206 if (nestingTable == null) {
207 computeNestingTable();
208 }
209 int parentGroup = nestingTable.get(i);
210 // insert the start and end events immediately before the end event for the parent group,
211 // if present; otherwise after all existing events for this position
212 List<Integer> s = actions.get(start);
213 if (s == null) {
214 s = new ArrayList<Integer>(4);
215 actions.put(start, s);
216 s.add(i);
217 s.add(-i);
218 } else {
219 int pos = s.size();
220 for (int e = 0; e < s.size(); e++) {
221 if (s.get(e) == -parentGroup) {
222 pos = e;
223 break;
224 }
225 }
226 s.add(pos, -i);
227 s.add(pos, i);
228 }
229
230 }
231 }
232
233 }
234 FastStringBuffer buff = new FastStringBuffer(current.length());
235 for (int i = 0; i < current.length() + 1; i++) {
236 List<Integer> events = actions.get(i);
237 if (events != null) {
238 if (buff.length() > 0) {
239 action.characters(buff);
240 buff.setLength(0);
241 }
242 for (Iterator<Integer> ii = events.iterator(); ii.hasNext(); ) {
243 int group = ii.next();
244 if (group > 0) {
245 action.onGroupStart(group);
246 } else {
247 action.onGroupEnd(-group);
248 }
249 }
250 }
251 if (i < current.length()) {
252 buff.append(current.charAt(i));
253 }
254 }
255 if (buff.length() > 0) {
256 action.characters(buff);
257 }
258 }
259
260 }
261
262 /**
263 * Compute a table showing for each captured group number (opening paren in the regex),
264 * the number of its parent group. This is done by reparsing the source of the regular
265 * expression. This is needed when the result of a match includes an empty group, to determine
266 * its position relative to other groups finishing at the same character position.
267 */
268
269 private void computeNestingTable() {
270 nestingTable = new IntToIntHashMap(16);
271 String s = pattern.pattern();
272 int[] stack = new int[s.length()];
273 int tos = 0;
274 int group = 1;
275 int inBrackets = 0;
276 stack[tos++] = 0;
277 for (int i = 0; i < s.length(); i++) {
278 char ch = s.charAt(i);
279 if (ch == '\'') {
280 i++;
281 } else if (ch == '[') {
282 inBrackets++;
283 } else if (ch == ']') {
284 inBrackets--;
285 } else if (ch == '(' && s.charAt(i + 1) != '?' && inBrackets == 0) {
286 nestingTable.put(group, stack[tos - 1]);
287 stack[tos++] = group++;
288 } else if (ch == ')' && inBrackets == 0) {
289 tos--;
290 }
291 }
292 }
293
294
295 }
296