public static String getTagAttrWhere ( StringBuilder page , final String tag , final String findAttr , final String whereAttr , final String whereVal ) { Pattern tagPattern = getWholeTagPattern ( tag ) ; Pattern findAttrPattern = getAttrPattern ( findAttr ) ; Pattern whereAttrPattern = getAttrPattern ( whereAttr ) ; Matcher tagMatcher = tagPattern . matcher ( page ) ; while ( tagMatcher . find ( ) ) { String wholeTag = tagMatcher . group ( ) ; Matcher whereAttrMatcher = whereAttrPattern . matcher ( wholeTag ) ; if ( whereAttrMatcher . find ( ) ) { String attrValue = whereAttrMatcher . group ( 1 ) ; attrValue = trimAttrValue ( attrValue ) ; if ( attrValue . compareToIgnoreCase ( whereVal ) == 0 ) { // this tag contains the right set, return the value for // the attribute findAttr: Matcher findAttrMatcher = findAttrPattern . matcher ( wholeTag ) ; String value = null ; if ( findAttrMatcher . find ( ) ) { value = findAttrMatcher . group ( 1 ) ; value = trimAttrValue ( value ) ; } return value ; } // not the tag we want... maybe there is another: loop } } return null ; }
Search through the HTML contained in page returning the value of a particular attribute . This version allows matching only tags that contain a particular attribute - value pair which is useful in extracting META tag values for example in returning the value of the content attribute in a META tag that also contains an attribute http - equiv with a value of Content - Type . All comparision is case - insensitive but the value returned is the original attribute value as unmolested as possible .