Guest User

Untitled

a guest
Jan 12th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. import re
  2.  
  3. p = '(\d+)'
  4. pgroups = '(\d+)-(\d+)-(\d+)'
  5. p2 = '-\d{2}-'
  6. ssn = '012-34-5678'
  7.  
  8. # Returns a list: [ '012', '34', '5678' ]
  9. matches_list = re.findall(p, ssn)
  10.  
  11. # Returns an iterator
  12. matches_it = re.finditer(p, ssn)
  13. for m in matches_it:
  14. print('{0}-{1}: {2}'.format(m.start(), m.end(), m.group(0)))
  15.  
  16. # re.match matches only the beginning of a string if starting position is not specified
  17. # re.search scans the whole string
  18. # So this does not match:
  19. match = re.match(p2, ssn)
  20.  
  21. # Which means this is None:
  22. type(match)
  23.  
  24. # While this successfully returns a match object
  25. match = re.search(p2, ssn)
  26. type(match)
  27. print('{0}-{1}: {2}'.format(match.start(), match.end(), match.group(0)))
  28.  
  29. # With multiple groups in a match object, .group(0) and .group() return the full set of matches
  30. # While .group(n) returns the nth group
  31. # And .groups() returns a tuple of the groups
  32. ssnmatch = re.search(pgroups, ssn)
  33. print('Match: {0}'.format(ssnmatch.group(0)))
  34. print('Tuple: {0}'.format(ssnmatch.groups()))
  35. for group in range(1, len(ssnmatch.groups()) + 1):
  36. print('Match group: {0}'.format(ssnmatch.group(group)))
Add Comment
Please, Sign In to add comment