#NEWLINE# def extract_regex( regex , text , encoding = 'utf-8' ) : #NEWLINE# #INDENT# 'Extract a list of unicode strings from the given text/encoding using the following policies:\n\n    * if the regex contains a named group called "extract" that will be returned\n    * if the regex contains multiple numbered groups, all those will be returned (flattened)\n    * if the regex doesn\'t contain any group the entire regex matching is returned\n    ' #NEWLINE# if isinstance ( regex , six . string_types ) : #NEWLINE# #INDENT# regex = re . compile ( regex , re . UNICODE ) #NEWLINE# #UNINDENT# try : #NEWLINE# #INDENT# strings = [ regex . search ( text ) . group ( 'extract' ) ] #NEWLINE# #UNINDENT# except : #NEWLINE# #INDENT# strings = regex . findall ( text ) #NEWLINE# #UNINDENT# strings = flatten ( strings ) #NEWLINE# if isinstance ( text , six . text_type ) : #NEWLINE# #INDENT# return [ replace_entities ( s , keep = [ 'lt' , 'amp' ] ) for s in strings ] #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# return [ replace_entities ( to_unicode ( s , encoding ) , keep = [ 'lt' , 'amp' ] ) for s in strings ]