1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.supercsv.cellprocessor.constraint;
17
18 import java.util.HashMap;
19 import java.util.Map;
20 import java.util.regex.Pattern;
21 import java.util.regex.PatternSyntaxException;
22
23 import org.supercsv.cellprocessor.CellProcessorAdaptor;
24 import org.supercsv.cellprocessor.ift.StringCellProcessor;
25 import org.supercsv.exception.SuperCsvCellProcessorException;
26 import org.supercsv.exception.SuperCsvConstraintViolationException;
27 import org.supercsv.util.CsvContext;
28
29
30
31
32
33
34
35
36 public class StrRegEx extends CellProcessorAdaptor implements StringCellProcessor {
37
38 private final String regex;
39 private final Pattern regexPattern;
40
41 private static final Map<String, String> REGEX_MSGS = new HashMap<String, String>();
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56 public StrRegEx(final String regex) {
57 super();
58 checkPreconditions(regex);
59 this.regexPattern = Pattern.compile(regex);
60 this.regex = regex;
61 }
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78 public StrRegEx(final String regex, final StringCellProcessor next) {
79 super(next);
80 checkPreconditions(regex);
81 this.regexPattern = Pattern.compile(regex);
82 this.regex = regex;
83 }
84
85
86
87
88
89
90
91
92
93
94
95 private static void checkPreconditions(final String regex) {
96 if( regex == null ) {
97 throw new NullPointerException("regex should not be null");
98 } else if( regex.length() == 0 ) {
99 throw new IllegalArgumentException("regex should not be empty");
100 }
101 }
102
103
104
105
106
107
108
109
110
111 public Object execute(final Object value, final CsvContext context) {
112 validateInputNotNull(value, context);
113
114 final boolean matches = regexPattern.matcher((String) value).matches();
115 if( !matches ) {
116 final String msg = REGEX_MSGS.get(regex);
117 if( msg == null ) {
118 throw new SuperCsvConstraintViolationException(String.format(
119 "'%s' does not match the regular expression '%s'", value, regex), context, this);
120 } else {
121 throw new SuperCsvConstraintViolationException(
122 String.format("'%s' does not match the constraint '%s' defined by the regular expression '%s'",
123 value, msg, regex), context, this);
124 }
125 }
126 return next.execute(value, context);
127 }
128
129
130
131
132
133
134
135
136
137
138
139 public static void registerMessage(String regex, String message) {
140 REGEX_MSGS.put(regex, message);
141 }
142
143 }