View Javadoc
1   /*
2    * Copyright 2010 Werner Guttmann
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  package org.exolab.castor.util;
15  
16  import java.util.regex.Pattern;
17  import java.util.regex.PatternSyntaxException;
18  
19  /**
20   * An implementation of {@link RegExpEvaluator} that uses the Java Regular Expression library.
21   * 
22   * @author <a href="mailto:george76@hotmail.com">George Varghese</a>
23   * @since 1.3.2
24   **/
25  public class SunRegExpEvaluator implements RegExpEvaluator {
26  
27    /**
28     * The Regular expression
29     **/
30    private Pattern _pattern;
31  
32    /**
33     * Sets the regular expression to match against during a call to #matches
34     * 
35     * @param rexpr the regular expression
36     **/
37    public void setExpression(String rexpr) {
38  
39      if (rexpr != null) {
40        try {
41          // -- patch and compile expression
42          _pattern = Pattern.compile(rexpr);
43        } catch (PatternSyntaxException ex) {
44          String err = "RegExp Syntax error: ";
45          err += ex.getMessage();
46          err += " ; error occured with the following " + "regular expression: " + rexpr;
47  
48          throw new IllegalArgumentException(err, ex);
49        }
50      }
51    }
52  
53    /**
54     * Returns true if the given String is matched by the regular expression of this RegExpEvaluator
55     * 
56     * @param value the String to check the production of
57     * @return true if the given string matches the regular expression of this RegExpEvaluator
58     * @see #setExpression
59     **/
60    public boolean matches(String value) {
61      if (_pattern != null) {
62        return _pattern.matcher(value).matches();
63      }
64      return true;
65    }
66  
67  }
68