Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- p = '(\d+)'
- pgroups = '(\d+)-(\d+)-(\d+)'
- p2 = '-\d{2}-'
- ssn = '012-34-5678'
- # Returns a list: [ '012', '34', '5678' ]
- matches_list = re.findall(p, ssn)
- # Returns an iterator
- matches_it = re.finditer(p, ssn)
- for m in matches_it:
- print('{0}-{1}: {2}'.format(m.start(), m.end(), m.group(0)))
- # re.match matches only the beginning of a string if starting position is not specified
- # re.search scans the whole string
- # So this does not match:
- match = re.match(p2, ssn)
- # Which means this is None:
- type(match)
- # While this successfully returns a match object
- match = re.search(p2, ssn)
- type(match)
- print('{0}-{1}: {2}'.format(match.start(), match.end(), match.group(0)))
- # With multiple groups in a match object, .group(0) and .group() return the full set of matches
- # While .group(n) returns the nth group
- # And .groups() returns a tuple of the groups
- ssnmatch = re.search(pgroups, ssn)
- print('Match: {0}'.format(ssnmatch.group(0)))
- print('Tuple: {0}'.format(ssnmatch.groups()))
- for group in range(1, len(ssnmatch.groups()) + 1):
- print('Match group: {0}'.format(ssnmatch.group(group)))
Add Comment
Please, Sign In to add comment