1 package net.sf.saxon.instruct; 2 import net.sf.saxon.om.ArrayIterator; 3 import net.sf.saxon.om.Item; 4 import net.sf.saxon.om.SequenceIterator; 5 import net.sf.saxon.om.EmptyIterator; 6 import net.sf.saxon.value.StringValue; 7 8 import java.util.regex.Matcher ; 9 import java.util.regex.Pattern ; 10 11 14 15 public class RegexIterator implements SequenceIterator { 16 17 private String theString; private Pattern pattern; private Matcher matcher; private String current; private String next; private int position = 0; private int prevEnd = 0; 26 33 34 public RegexIterator (String string, Pattern pattern) { 35 theString = string; 36 this.pattern = pattern; 37 matcher = pattern.matcher(string); 38 next = null; 39 } 40 41 45 46 public Item next() { 47 if (next == null && prevEnd >= 0) { 48 if (matcher.find()) { 50 int start = matcher.start(); 51 int end = matcher.end(); 52 if (prevEnd == start) { 53 next = null; 55 current = theString.substring(start, end); 56 prevEnd = end; 57 } else { 58 current = theString.substring(prevEnd, start); 60 next = theString.substring(start, end); 61 } 62 } else { 63 if (prevEnd < theString.length()) { 65 current = theString.substring(prevEnd); 66 next = null; 67 } else { 68 current = null; 70 position = -1; 71 prevEnd = -1; 72 return null; 73 } 74 prevEnd = -1; 75 } 76 } else { 77 if (prevEnd >= 0) { 79 current = next; 80 next = null; 81 prevEnd = matcher.end(); 82 } else { 83 current = null; 84 position = -1; 85 return null; 86 } 87 } 88 position++; 89 return StringValue.makeStringValue(current); 90 } 91 92 96 97 public Item current() { 98 return StringValue.makeStringValue(current); 99 } 100 101 105 106 public int position() { 107 return position; 108 } 109 110 114 115 public SequenceIterator getAnother() { 116 return new RegexIterator(theString, pattern); 117 } 118 119 128 129 public int getProperties() { 130 return 0; 131 } 132 133 139 140 public boolean isMatching() { 141 return next == null && prevEnd >= 0; 142 } 143 144 150 151 public String getRegexGroup(int number) { 152 if (!isMatching()) return null; 153 if (number > matcher.groupCount() || number < 0) return ""; 154 String s = matcher.group(number); 155 if (s==null) return ""; 156 return s; 157 } 158 159 163 164 public SequenceIterator getRegexGroupIterator() { 165 int c = matcher.groupCount(); 166 if (c == 0) { 167 return EmptyIterator.getInstance(); 168 } else { 169 StringValue[] groups = new StringValue[c]; 170 for (int i=1; i<=groups.length; i++) { 171 groups[i-1] = StringValue.makeStringValue(matcher.group(i)); 172 } 173 return new ArrayIterator(groups); 174 } 175 } 176 177 } 178 179 | Popular Tags |