01: /*
02: * RegexModifier.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.db.importer.modifier;
13:
14: import java.util.HashMap;
15: import java.util.Map;
16: import java.util.regex.Matcher;
17: import java.util.regex.Pattern;
18: import java.util.regex.PatternSyntaxException;
19: import workbench.db.ColumnIdentifier;
20:
21: /**
22: *
23: * @author support@sql-workbench.net
24: */
25: public class RegexModifier implements ImportValueModifier {
26: public Map<ColumnIdentifier, RegexDef> limits = new HashMap<ColumnIdentifier, RegexDef>();
27:
28: public RegexModifier() {
29: }
30:
31: public int getSize() {
32: return limits.size();
33: }
34:
35: /**
36: * Define regex replacement for a column.
37: * An existing mapping for that column will be overwritten.
38: *
39: * @param col the column for which to apply the substring
40: * @param regex the regular expression to search for
41: * @param replacement the replacement for the regex
42: */
43: public void addDefinition(ColumnIdentifier col, String regex,
44: String replacement) throws PatternSyntaxException {
45: RegexDef def = new RegexDef(regex, replacement);
46: this .limits.put(col.createCopy(), def);
47: }
48:
49: public String modifyValue(ColumnIdentifier col, String value) {
50: if (value == null)
51: return null;
52: RegexDef def = this .limits.get(col);
53: if (def != null) {
54: Matcher m = def.regex.matcher(value);
55: return m.replaceAll(def.replacement);
56: }
57: return value;
58: }
59:
60: private static class RegexDef {
61: Pattern regex;
62: String replacement;
63:
64: public RegexDef(String exp, String repl)
65: throws PatternSyntaxException {
66: regex = Pattern.compile(exp);
67: replacement = repl;
68: }
69: }
70: }
|