1 7 package com.ibm.icu.text; 8 import com.ibm.icu.impl.Utility; 9 10 class Quantifier implements UnicodeMatcher { 11 12 private UnicodeMatcher matcher; 13 14 private int minCount; 15 16 private int maxCount; 17 18 21 public static final int MAX = Integer.MAX_VALUE; 22 23 public Quantifier(UnicodeMatcher theMatcher, 24 int theMinCount, int theMaxCount) { 25 if (theMatcher == null || minCount < 0 || maxCount < 0 || minCount > maxCount) { 26 throw new IllegalArgumentException (); 27 } 28 matcher = theMatcher; 29 minCount = theMinCount; 30 maxCount = theMaxCount; 31 } 32 33 36 public int matches(Replaceable text, 37 int[] offset, 38 int limit, 39 boolean incremental) { 40 int start = offset[0]; 41 int count = 0; 42 while (count < maxCount) { 43 int pos = offset[0]; 44 int m = matcher.matches(text, offset, limit, incremental); 45 if (m == U_MATCH) { 46 ++count; 47 if (pos == offset[0]) { 48 break; 51 } 52 } else if (incremental && m == U_PARTIAL_MATCH) { 53 return U_PARTIAL_MATCH; 54 } else { 55 break; 56 } 57 } 58 if (incremental && offset[0] == limit) { 59 return U_PARTIAL_MATCH; 60 } 61 if (count >= minCount) { 62 return U_MATCH; 63 } 64 offset[0] = start; 65 return U_MISMATCH; 66 } 67 68 71 public String toPattern(boolean escapeUnprintable) { 72 StringBuffer result = new StringBuffer (); 73 result.append(matcher.toPattern(escapeUnprintable)); 74 if (minCount == 0) { 75 if (maxCount == 1) { 76 return result.append('?').toString(); 77 } else if (maxCount == MAX) { 78 return result.append('*').toString(); 79 } 80 } else if (minCount == 1 && maxCount == MAX) { 82 return result.append('+').toString(); 83 } 84 result.append('{'); 85 Utility.appendNumber(result, minCount); 86 result.append(','); 87 if (maxCount != MAX) { 88 Utility.appendNumber(result, maxCount); 89 } 90 result.append('}'); 91 return result.toString(); 92 } 93 94 97 public boolean matchesIndexValue(int v) { 98 return (minCount == 0) || matcher.matchesIndexValue(v); 99 } 100 101 108 public void addMatchSetTo(UnicodeSet toUnionTo) { 109 if (maxCount > 0) { 110 matcher.addMatchSetTo(toUnionTo); 111 } 112 } 113 } 114 115 | Popular Tags |