View Javadoc

1   /*
2    * Copyright 2002-2009 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
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  
17  package net.sf.json.regexp;
18  
19  import org.apache.commons.lang.exception.NestableRuntimeException;
20  import org.apache.oro.text.regex.MalformedPatternException;
21  import org.apache.oro.text.regex.Pattern;
22  import org.apache.oro.text.regex.PatternMatcher;
23  import org.apache.oro.text.regex.Perl5Compiler;
24  import org.apache.oro.text.regex.Perl5Matcher;
25  
26  /**
27   * Jakarta-oro RegexpMatcher Implementation.<br>
28   * Runs on older JVMs (1.3.1). You must have oro-2.0.8.jar configured in your classpath.
29   * 
30   * @author Andres Almiray <aalmiray@users.sourceforge.net>
31   */
32  public class Perl5RegexpMatcher implements RegexpMatcher {
33     private static final Perl5Compiler compiler = new Perl5Compiler();
34     private Pattern pattern;
35  
36     public Perl5RegexpMatcher( String pattern ) {
37        this( pattern, false );
38     }
39  
40     public Perl5RegexpMatcher( String pattern, boolean multiline ) {
41        try {
42           if( multiline ) {
43              this.pattern = compiler.compile( pattern, Perl5Compiler.READ_ONLY_MASK | Perl5Compiler.MULTILINE_MASK );
44           } else {
45              this.pattern = compiler.compile( pattern, Perl5Compiler.READ_ONLY_MASK );
46           }
47        } catch( MalformedPatternException mpe ) {
48           throw new NestableRuntimeException( mpe );
49        }
50     }
51  
52     public String getGroupIfMatches( String str, int group ) {
53        PatternMatcher matcher = new Perl5Matcher();
54        if( matcher.matches( str, pattern ) ) {
55           return matcher.getMatch().group( 1 );
56        }
57        return "";
58     }
59  
60     public boolean matches( String str ) {
61        return new Perl5Matcher().matches( str, pattern );
62     }
63  }