1 package org.unicode.cldr.unittest;
2 
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.regex.Matcher;
6 import java.util.regex.Pattern;
7 
8 import com.ibm.icu.impl.Row;
9 import com.ibm.icu.impl.Row.R2;
10 import com.ibm.icu.text.Transform;
11 
12 public class RegexTransform implements Transform<String, String> {
13 
14     public enum Processing {
15         FIRST_MATCH, ONE_PASS, RECURSIVE
16     }
17 
18     private final Processing processing;
19     private final List<Row.R2<Matcher, String>> entries = new ArrayList<Row.R2<Matcher, String>>();
20 
21     @Override
transform(String source)22     public String transform(String source) {
23         main: while (true) {
24             for (R2<Matcher, String> entry : entries) {
25                 Matcher matcher = entry.get0();
26                 if (matcher.reset(source).find()) {
27                     String replacement = entry.get1();
28                     source = matcher.replaceAll(replacement);
29                     switch (processing) {
30                     case RECURSIVE:
31                         continue main;
32                     case FIRST_MATCH:
33                         break main;
34                     case ONE_PASS: // fall through and continue;
35                     }
36                 }
37             }
38             break;
39         }
40         return source;
41     }
42 
RegexTransform(Processing processing)43     public RegexTransform(Processing processing) {
44         this.processing = processing;
45     }
46 
add(String pattern, String replacement)47     public RegexTransform add(String pattern, String replacement) {
48         entries.add(Row.of(
49             Pattern.compile(pattern, Pattern.COMMENTS).matcher(""),
50             replacement));
51         return this;
52     }
53 }