|
15 | 15 | */
|
16 | 16 | package org.culturegraph.mf.util.tries;
|
17 | 17 |
|
| 18 | +import java.util.Collections; |
| 19 | +import java.util.Comparator; |
18 | 20 | import java.util.List;
|
19 | 21 | import java.util.Map;
|
20 | 22 | import java.util.Map.Entry;
|
21 | 23 |
|
| 24 | +import org.culturegraph.mf.util.tries.SetMatcher.Match; |
| 25 | + |
22 | 26 | /**
|
23 | 27 | * @author Markus Michael Geipel
|
24 |
| - * |
| 28 | + * |
25 | 29 | */
|
26 | 30 | public final class SetReplacer {
|
27 | 31 | private final SetMatcher<String> matcher = new SetMatcher<String>();
|
28 |
| - |
29 |
| - public void addReplacement(final String key, final String with){ |
| 32 | + |
| 33 | + public void addReplacement(final String key, final String with) { |
30 | 34 | matcher.put(key, with);
|
31 | 35 | }
|
32 |
| - |
33 |
| - public void addReplacements(final Map<String, String> replacements){ |
| 36 | + |
| 37 | + public void addReplacements(final Map<String, String> replacements) { |
34 | 38 | for (Entry<String, String> entry : replacements.entrySet()) {
|
35 | 39 | addReplacement(entry.getKey(), entry.getValue());
|
36 | 40 | }
|
37 | 41 | }
|
38 |
| - |
39 |
| - |
40 |
| - public String replaceIn(final String text){ |
| 42 | + |
| 43 | + public String replaceIn(final String text) { |
41 | 44 | final List<SetMatcher.Match<String>> matches = matcher.match(text);
|
42 | 45 | final StringBuilder builder = new StringBuilder();
|
43 |
| - |
| 46 | + |
44 | 47 | int lastCut = 0;
|
| 48 | + |
| 49 | + Collections.sort(matches, new Comparator<SetMatcher.Match<String>>() { |
| 50 | + @Override |
| 51 | + public int compare(final Match<String> o1, final Match<String> o2) { |
| 52 | + final int result; |
| 53 | + final int delta = o1.getStart() - o2.getStart(); |
| 54 | + if (delta < 0) { |
| 55 | + result = -1; |
| 56 | + } else if (delta > 0) { |
| 57 | + result = 1; |
| 58 | + } else { |
| 59 | + if (o1.getLength() > o2.getLength()) { |
| 60 | + result = -1; |
| 61 | + } else { |
| 62 | + result = 1; |
| 63 | + } |
| 64 | + } |
| 65 | + return result; |
| 66 | + } |
| 67 | + |
| 68 | + }); |
| 69 | + |
45 | 70 | for (SetMatcher.Match<String> match : matches) {
|
46 |
| - |
47 |
| - if(match.getStart()<lastCut){ |
| 71 | + |
| 72 | + if (match.getStart() < lastCut) { |
48 | 73 | continue;
|
49 | 74 | }
|
50 |
| - |
51 |
| - //System.out.println(match.getStart() + " "+ match.getValue() +" "+ match.getLength()); |
52 |
| - |
| 75 | + |
| 76 | + // System.out.println(match.getStart() + " "+ match.getValue() +" "+ |
| 77 | + // match.getLength()); |
| 78 | + |
53 | 79 | builder.append(text.substring(lastCut, match.getStart()));
|
54 | 80 | builder.append(match.getValue());
|
55 |
| - |
| 81 | + |
56 | 82 | lastCut = match.getStart() + match.getLength();
|
57 | 83 | }
|
58 | 84 | builder.append(text.substring(lastCut, text.length()));
|
59 |
| - |
| 85 | + |
60 | 86 | return builder.toString();
|
61 | 87 | }
|
62 |
| - |
| 88 | + |
63 | 89 | }
|
0 commit comments