Search This Blog

Tuesday, February 10, 2009

Regular Expression

Regular Expression is really cool, All should know it;) Initially you might feel that its too complex but when u get into it u feel its look complex but it is really cool and easy to use. It completes big task in few lines....... Its really great;) Below is my first function in Python which i have used to search for a String using '*' to escape and search in string. Cheers Python B) def SearchString(pattern,string): ulist = pattern.split('*') if len(ulist) > 1: k = '^' + ulist[0] + '[\w|\_|\-]*' + ''.join([ i + '[\w|\_|\-]*' for i in ulist[1:-1]]) + ulist[-1] + '$' print k if re.search(k,user) != None: return "Found" else: return "Not Found" elif ulist == string: return "Found" else: return "Not Found" >>> SearchUser('vin*jda*is','vinojdavis') ^vin[\w|\_|\-]*jda[\w|\_|\-]*is$ 'Found' >>> SearchUser('vi**jda*is','vinojdavis') ^vi[\w|\_|\-]*[\w|\_|\-]*jda[\w|\_|\-]*is$ 'Found' >>> SearchUser('vin*jda*is','viojdavis') ^vin[\w|\_|\-]*jda[\w|\_|\-]*is$ 'Not Found'

No comments: