#NEWLINE# def find_tag( string , direction , tag_name = '' ) : #NEWLINE# #INDENT# regexString = ( ( ( ( '<\\s*' + tag_name ) + '.*?>|<\\/\\s*' ) + tag_name ) + '\\s*>' ) #NEWLINE# regex = re . compile ( regexString ) #NEWLINE# target_tag_type = ( ( ( direction == 'forward' ) and 'closing' ) or 'opening' ) #NEWLINE# target_tag_type_counterpart = ( ( ( direction == 'forward' ) and 'opening' ) or 'closing' ) #NEWLINE# symbolStack = [ ] #NEWLINE# result = list ( regex . finditer ( string ) ) #NEWLINE# if ( direction == 'backward' ) : #NEWLINE# #INDENT# result . reverse ( ) #NEWLINE# #UNINDENT# for m in result : #NEWLINE# #INDENT# tag_string = m . group ( ) #NEWLINE# if tag_string . startswith ( '<!--' ) : #NEWLINE# #INDENT# continue #NEWLINE# #UNINDENT# tag_type = get_tag_properties ( tag_string ) [ 'type' ] #NEWLINE# if ( tag_type == result ) : #NEWLINE# #INDENT# if ( len ( symbolStack ) == 0 ) : #NEWLINE# #INDENT# return { #NEWLINE# #INDENT# 'start' : m . start ( ) , #NEWLINE# 'end' : m . end ( ) , #NEWLINE# 'name' : get_tag_properties ( tag_string ) [ 'name' ] , #NEWLINE# #UNINDENT# } #NEWLINE# #UNINDENT# symbolStack . pop ( ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# if ( tag_type == target_tag_type_counterpart ) : #NEWLINE# #INDENT# symbolStack . append ( tag_type )