1 package com.github.mygreen.supercsv.cellprocessor.conversion;
2
3 import java.util.regex.Matcher;
4 import java.util.regex.Pattern;
5
6 import org.supercsv.cellprocessor.CellProcessorAdaptor;
7 import org.supercsv.cellprocessor.ift.CellProcessor;
8 import org.supercsv.cellprocessor.ift.StringCellProcessor;
9 import org.supercsv.util.CsvContext;
10
11
12
13
14
15
16
17
18
19 public class RegexReplace extends CellProcessorAdaptor implements StringCellProcessor {
20
21 private final Pattern pattern;
22
23 private final String replacement;
24
25 private final boolean partialMatched;
26
27
28
29
30
31
32
33
34
35 public RegexReplace(final Pattern pattern, final String replacement, final boolean partialMatched) {
36 super();
37 checkPreconditions(pattern, replacement);
38 this.pattern = pattern;
39 this.replacement = replacement;
40 this.partialMatched = partialMatched;
41 }
42
43
44
45
46
47
48
49
50
51
52 public RegexReplace(final Pattern pattern, final String replacement, final boolean partialMatched,
53 final StringCellProcessor next) {
54 super(next);
55 checkPreconditions(pattern, replacement);
56 this.pattern = pattern;
57 this.replacement = replacement;
58 this.partialMatched = partialMatched;
59 }
60
61
62
63
64
65
66
67
68 private static void checkPreconditions(final Pattern pattern, final String replacement) {
69 if(pattern == null ) {
70 throw new NullPointerException("regex should not be null");
71 }
72
73 if(replacement == null) {
74 throw new NullPointerException("replacement should not be null");
75 }
76 }
77
78 @Override
79 public <T> T execute(final Object value, final CsvContext context) {
80
81 if(value == null) {
82 return next.execute(value, context);
83 }
84
85 final Matcher matcher = pattern.matcher(value.toString());
86 final boolean matched = partialMatched ? matcher.find() : matcher.matches();
87 if(matched) {
88 final String result = matcher.replaceAll(replacement);
89 return next.execute(result, context);
90 }
91
92 return next.execute(value, context);
93 }
94
95
96
97
98
99 public String getRegex() {
100 return pattern.toString();
101 }
102
103
104
105
106
107 public int getFlags() {
108 return pattern.flags();
109 }
110
111
112
113
114
115 public String getReplacement() {
116 return replacement;
117 }
118
119
120
121
122
123 public boolean isPartialMatched() {
124 return partialMatched;
125 }
126
127
128 }