01: /*
02: * Copyright 2004, 2005, 2006 Odysseus Software GmbH
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package de.odysseus.calyxo.forms.match;
17:
18: import java.util.regex.Matcher;
19: import java.util.regex.Pattern;
20:
21: /**
22: * Matcher using a regular expression.
23: *
24: * @author Christoph Beck
25: */
26: public class RegExpMatcher extends SimpleMatcher {
27: private Pattern pattern;
28:
29: /**
30: * Default constructor.
31: */
32: public RegExpMatcher() {
33: super ();
34: }
35:
36: /**
37: * Constructor.
38: */
39: public RegExpMatcher(String pattern) throws Exception {
40: super ();
41:
42: setPattern(pattern);
43: }
44:
45: /**
46: * Apply pattern to specified value.
47: * @return matched part of input (null if value does not match pattern)
48: */
49: public String match(String value) {
50: if (value.length() == 0) {
51: return value;
52: }
53: Matcher matcher = pattern.matcher(value.subSequence(0, value
54: .length()));
55: if (!matcher.find())
56: return null;
57: return matcher.group();
58: }
59:
60: /**
61: * Get the pattern property
62: */
63: public String getPattern() {
64: return pattern.pattern();
65: }
66:
67: /**
68: * Get the pattern property
69: */
70: public void setPattern(String pattern) throws Exception {
71: this .pattern = Pattern.compile(pattern);
72: }
73:
74: protected String paramsToString() {
75: return ", pattern: "
76: + (pattern == null ? "" : pattern.pattern());
77: }
78:
79: /**
80: * This matcher is thread-save, so answer <code>true</code>
81: */
82: public boolean isSharable() {
83: return true;
84: }
85: }
|