2 *******************************************************************************
\r
3 * Copyright (C) 2001-2010, International Business Machines Corporation and *
\r
4 * others. All Rights Reserved. *
\r
5 *******************************************************************************
\r
7 package com.ibm.icu.text;
\r
8 import com.ibm.icu.impl.Utility;
\r
10 class Quantifier implements UnicodeMatcher {
\r
12 private UnicodeMatcher matcher;
\r
14 private int minCount;
\r
16 private int maxCount;
\r
19 * Maximum count a quantifier can have.
\r
21 public static final int MAX = Integer.MAX_VALUE;
\r
23 public Quantifier(UnicodeMatcher theMatcher,
\r
24 int theMinCount, int theMaxCount) {
\r
25 if (theMatcher == null || minCount < 0 || maxCount < 0 || minCount > maxCount) {
\r
26 throw new IllegalArgumentException();
\r
28 matcher = theMatcher;
\r
29 minCount = theMinCount;
\r
30 maxCount = theMaxCount;
\r
34 * Implement UnicodeMatcher API.
\r
36 public int matches(Replaceable text,
\r
39 boolean incremental) {
\r
40 int start = offset[0];
\r
42 while (count < maxCount) {
\r
43 int pos = offset[0];
\r
44 int m = matcher.matches(text, offset, limit, incremental);
\r
47 if (pos == offset[0]) {
\r
48 // If offset has not moved we have a zero-width match.
\r
49 // Don't keep matching it infinitely.
\r
52 } else if (incremental && m == U_PARTIAL_MATCH) {
\r
53 return U_PARTIAL_MATCH;
\r
58 if (incremental && offset[0] == limit) {
\r
59 return U_PARTIAL_MATCH;
\r
61 if (count >= minCount) {
\r
69 * Implement UnicodeMatcher API
\r
71 public String toPattern(boolean escapeUnprintable) {
\r
72 StringBuilder result = new StringBuilder();
\r
73 result.append(matcher.toPattern(escapeUnprintable));
\r
74 if (minCount == 0) {
\r
75 if (maxCount == 1) {
\r
76 return result.append('?').toString();
\r
77 } else if (maxCount == MAX) {
\r
78 return result.append('*').toString();
\r
80 // else fall through
\r
81 } else if (minCount == 1 && maxCount == MAX) {
\r
82 return result.append('+').toString();
\r
85 result.append(Utility.hex(minCount,1));
\r
87 if (maxCount != MAX) {
\r
88 result.append(Utility.hex(maxCount,1));
\r
91 return result.toString();
\r
95 * Implement UnicodeMatcher API
\r
97 public boolean matchesIndexValue(int v) {
\r
98 return (minCount == 0) || matcher.matchesIndexValue(v);
\r
102 * Implementation of UnicodeMatcher API. Union the set of all
\r
103 * characters that may be matched by this object into the given
\r
105 * @param toUnionTo the set into which to union the source characters
\r
106 * @returns a reference to toUnionTo
\r
108 public void addMatchSetTo(UnicodeSet toUnionTo) {
\r
109 if (maxCount > 0) {
\r
110 matcher.addMatchSetTo(toUnionTo);
\r