001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.shiro.util; 020 021import java.util.regex.Pattern; 022import java.util.regex.Matcher; 023 024/** 025 * {@code PatternMatcher} implementation that uses standard {@link java.util.regex} objects. 026 * 027 * @see Pattern 028 * @since 1.0 029 */ 030public class RegExPatternMatcher implements PatternMatcher { 031 032 private static final int DEFAULT = Pattern.DOTALL; 033 034 private static final int CASE_INSENSITIVE = DEFAULT | Pattern.CASE_INSENSITIVE; 035 036 private boolean caseInsensitive; 037 038 /** 039 * Simple implementation that merely uses the default pattern comparison logic provided by the 040 * JDK. 041 * <p/>This implementation essentially executes the following: 042 * <pre> 043 * Pattern p = Pattern.compile(pattern, Pattern.DOTALL); 044 * Matcher m = p.matcher(source); 045 * return m.matches();</pre> 046 * 047 * @param pattern the pattern to match against 048 * @param source the source to match 049 * @return {@code true} if the source matches the required pattern, {@code false} otherwise. 050 */ 051 public boolean matches(String pattern, String source) { 052 if (pattern == null) { 053 throw new IllegalArgumentException("pattern argument cannot be null."); 054 } 055 Pattern p = Pattern.compile(pattern, caseInsensitive ? CASE_INSENSITIVE : DEFAULT); 056 Matcher m = p.matcher(source); 057 return m.matches(); 058 } 059 060 /** 061 * Returns true if regex match should be case-insensitive. 062 * 063 * @return true if regex match should be case-insensitive. 064 */ 065 public boolean isCaseInsensitive() { 066 return caseInsensitive; 067 } 068 069 /** 070 * Adds the Pattern.CASE_INSENSITIVE flag when compiling patterns. 071 * 072 * @param caseInsensitive true if patterns should match case-insensitive. 073 */ 074 public void setCaseInsensitive(boolean caseInsensitive) { 075 this.caseInsensitive = caseInsensitive; 076 } 077}