def _reverse_url_pattern(url_pattern, *args):
 group_index = [0]
 def expand_group(match):
  group = match.group(1)
  try:
   value = str(args[group_index[0]])
   group_index[0] += 1
  except IndexError:
   raise CannotReversePattern('Not enough arguments in url tag')
  if (not re.match((group + '$'), value)):
   raise CannotReversePattern(("Value %r doesn't match (%r)" % (value, group)))
  return value
 result = re.sub('\\(([^)]+)\\)', expand_group, url_pattern.pattern)
 result = result.replace('^', '')
 result = result.replace('$', '')
 return result

def _reverse_url_pattern ( url_pattern , * args ) : group_index = [ 0 ] def expand_group ( match ) : group = match . group ( 1 ) try : value = str ( args [ group_index [ 0 ] ] ) group_index [ 0 ] += 1 except IndexError : raise CannotReversePattern ( 'Not enough arguments in url tag' ) if ( not re . match ( ( group + '$' ) , value ) ) : raise CannotReversePattern ( ( "Value %r doesn't match (%r)" % ( value , group ) ) ) return value result = re . sub ( '\\(([^)]+)\\)' , expand_group , url_pattern . pattern ) result = result . replace ( '^' , '' ) result = result . replace ( '$' , '' ) return result
turns a regex that matches a url back into a url by replacing the url patterns groups with the given args .