Grep using Python

Thanks to Adam Ginsburg

#py grep command 
#sample command: grep("^x",dir()) 
#syntax: grep(regexp_string,list_of_strings_to_search) 
import re 
def grep(string,list): 
	expr = re.compile(string) 
	for text in list: 
		match = 
		if match != None: 
			print match.string 
# Two alternate solutions, courtesy of Gene H 
# These are more elegant, and more detailed descriptions can be found here: 
def grep(string,list): 
	expr = re.compile(string) 
	return [elem for elem in list if expr.match(elem)] 
def grep(string,list): 
	expr = re.compile(string) 
	return filter(,list) 
# Note a subtle difference between the above two: 
# because the first uses expr.match(), it will only return exact matches 
# while the latter will return a list containing strings that contain the 
# search string in any position 
# e.g.: 
# list = ['normalize','size','nonzero','zenith'] 
# grep('ze',list) # First one returns: ['zenith'] 
# Second one returns: ['normalize','size','nonzero','zenith']

pythongrep.txt · Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0