Advertisement
Guest User

Regex Search

a guest
Aug 23rd, 2017
1,596
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. # Opens all .txt files in a folder and
  2. # searches for any line that matches
  3. # a user-supplied regular expression
  4.  
  5. import re, os
  6.  
  7. textFiles = os.listdir('C:\\Users\\Melina\\AppData\\Local\\Programs\\Python\\Python36-32\\Projects\\Automate the Boring Stuff')
  8.  
  9. print('What do you want to search for?')
  10. userReg = str(input())
  11.  
  12. if userReg is 'email':
  13.     stringRegex = re.compile(r'[a-z0-9]+((\.|\_)[a-z0-9]+)*@[a-z0-9]+(\.[a-z0-9]+)*(\.[a-z0-9]{2,20})')
  14.     #fileRegex = re.compile(r'\w+\.txt')
  15. elif userReg is 'phone':
  16.     stringRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
  17.     #fileRegex = re.compile(r'\w+\.txt')
  18. fileRegex = re.compile(r'\w+\.txt')
  19.  
  20.  
  21. for i in range(len(textFiles)):
  22.     if fileRegex.search(textFiles[i]):
  23.         openFile = open('C:\\Users\\Melina\\AppData\\Local\\Programs\\Python\\Python36-32\\Projects\\Automate the Boring Stuff\\' +textFiles[i])
  24.         readFile = openFile.readlines()
  25.         for line in range(len(readFile)):
  26.             r = 0
  27.             if stringRegex.search(readFile[r]):
  28.                 print(readFile[r])
  29.                 r = r+1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement