def grep(pattern, items, squash=True):
 isdict = (type(items) is dict)
 if (pattern in __grep_cache):
  regex = __grep_cache[pattern]
 else:
  regex = __grep_cache[pattern] = re.compile(pattern)
 matched = []
 matchdict = {}
 for item in items:
  match = regex.match(item)
  if (not match):
   continue
  groups = match.groups()
  if (not groups):
   subitems = match.group(0)
  elif (len(groups) == 1):
   subitems = groups[0]
  else:
   subitems = list(groups)
  if isdict:
   matchdict[item] = items[item]
  else:
   matched.append(subitems)
 if isdict:
  return matchdict
 elif (squash and (len(matched) == 1)):
  return matched[0]
 else:
  return matched

def grep ( pattern , items , squash = True ) : isdict = ( type ( items ) is dict ) if ( pattern in __grep_cache ) : regex = __grep_cache [ pattern ] else : regex = __grep_cache [ pattern ] = re . compile ( pattern ) matched = [ ] matchdict = { } for item in items : match = regex . match ( item ) if ( not match ) : continue groups = match . groups ( ) if ( not groups ) : subitems = match . group ( 0 ) elif ( len ( groups ) == 1 ) : subitems = groups [ 0 ] else : subitems = list ( groups ) if isdict : matchdict [ item ] = items [ item ] else : matched . append ( subitems ) if isdict : return matchdict elif ( squash and ( len ( matched ) == 1 ) ) : return matched [ 0 ] else : return matched
search for ports using a regular expression .