Advertisement
johnmahugu

PYTHON >>> regex example

May 6th, 2016
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. # regex examples
  2. # For reference: http://www.regular-expressions.info/reference.html/
  3. # To test regexes: http://regexpal.com/
  4.  
  5. import re
  6.  
  7. # text to parse
  8. text1 = 'Monday, June 4, 1997, 2:38 p.m.'
  9. text2 = 'Thursday, March 31, 2011, 12:38 a.m.'
  10.  
  11. # match the time
  12. time1 = re.search('\d{1,2}:\d{2} (a.m.|p.m.)', text1)
  13. time2 = re.search('\d{1,2}:\d{2} (a.m.|p.m.)', text2)
  14.  
  15. print 'The time is ' + time1.group()
  16. print 'The time is ' + time2.group()
  17.  
  18. # match the day
  19. day1 = re.search('[^,]*', text1)
  20. day2 = re.search('[^,]*', text2)
  21.  
  22. print 'The day is ' + day1.group()
  23. print 'The day is ' + day2.group()
  24.  
  25. # match the date
  26. date1 = re.search('\w+ \d{1,2}, \d{4}', text1)
  27. date2 = re.search('\w+ \d{1,2}, \d{4}', text2)
  28.  
  29. print 'The date is ' + date1.group()
  30. print 'The date is ' + date2.group()
  31.  
  32. # match it all
  33. match1 = re.search('([^,]*), (\w+ \d{1,2}, \d{4}), (\d{1,2}:\d{2}) (a.m.|p.m.)', text1)
  34. match2 = re.search('([^,]*), (\w+ \d{1,2}, \d{4}), (\d{1,2}:\d{2}) (a.m.|p.m.)', text2)
  35.  
  36. print 'Day: ' + match1.group(1) + '; Date: ' + match1.group(2) +  \
  37.       '; Time: ' + match1.group(3) + ' ' + match1.group(4)
  38. print 'Day: ' + match2.group(1) + '; Date: ' + match2.group(2) +  \
  39.       '; Time: ' + match2.group(3) + ' ' + match2.group(4)
  40.  
  41. # Another example
  42. form1 = 'Name: Bob Michaels'
  43. form2 = 'Name: Pam Wells'
  44. form3 = 'Name: Bono'
  45.  
  46. namematch1 = re.search('Name: (.*)', form1)
  47. namematch2 = re.search('Name: (.*)', form2)
  48. namematch3 = re.search('Name: (.*)', form3)
  49.  
  50. print namematch1.group(1)
  51. print namematch2.group(1)
  52. print namematch3.group(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement