1 /** 2 * 3 * Licensed to the Apache Software Foundation (ASF) under one or more 4 * contributor license agreements. See the NOTICE file distributed with 5 * this work for additional information regarding copyright ownership. 6 * The ASF licenses this file to You under the Apache License, Version 2.0 7 * (the "License"); you may not use this file except in compliance with 8 * the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 package org.apache.maven.doxia.linkcheck.validation; 19 20 import java.util.regex.Matcher; 21 import java.util.regex.Pattern; 22 23 /** 24 * A helper class to test if some content matches the given HTML anchor 25 */ 26 public class Anchors 27 { 28 /** 29 * Returns true if the given anchor can be found in the content markup. 30 * 31 * @param content the content string. 32 * @param anchor the anchor to match. 33 * 34 * @return true if the given anchor can be found in the content markup. 35 */ 36 public static boolean matchesAnchor( String content, String anchor ) 37 { 38 if ( content != null && anchor.length() > 0 ) { 39 // can use name or id attributes and also can use single or double quotes with whitespace around the = 40 String regex = "(?i)(name|id)(?-i)\\s*=\\s*('|\")" + escapeBrackets( anchor ) + "('|\")"; 41 Pattern pattern = Pattern.compile( regex ); 42 Matcher matcher = pattern.matcher( content ); 43 return matcher.find(); 44 } 45 return false; 46 } 47 48 // for javadoc links, see DOXIA-410 49 private static String escapeBrackets( String content ) 50 { 51 final String escaped = content.replace( "(", "\\(" ).replace( ")", "\\)" ); 52 return escaped.replace( "[", "\\[" ).replace( "]", "\\]" ); 53 } 54 55 private Anchors() 56 { 57 // utility class 58 } 59 }