Reputation: 361
I am learning about Regex and am stuck with this code:
import re
resume = '''
(738) 383-5729
(373) 577-0492
(403) 443-2759
(375) 880-8576
(641) 576-2342
(951) 268-8744
'''
phoneRegex = re.compile(r'\d')
mo = phoneRegex.findall(resume)
print(mo.group())
When I try with search
instead of findall
, it works. But it can't find any match with findall
.
What am I doing wrong?
Upvotes: 3
Views: 1194
Reputation: 527
Re.findall()
module is used when you want to iterate over the lines by line, it will return a list of all the matches not group.
So in your case it returns as list
print(mo[0])
Upvotes: -2
Reputation: 26159
Since (it looks like) you're just out for the numbers, you could do something like
>>> [''.join(c for c in l if c in '0123456789') for l in resume.strip().splitlines()]
['7383835729', '3735770492', '4034432759', '3758808576', '6415762342', '9512688744']
That might save you some trouble from internationally formed numbers (such as +46-(0)7-08/123 456
and the like).
Upvotes: 1
Reputation: 98921
It seems that you're trying to match phone numbers in resume
, for that you can use:
resume = '''
(738) 383-5729
(373) 577-0492
(403) 443-2759
(375) 880-8576
(641) 576-2342
(951) 268-8744
'''
mo = re.findall(r'\(\d{3}\) \d{3}-\d{4}', resume)
for x in mo:
print(x)
Output:
(738) 383-5729
(373) 577-0492
(403) 443-2759
(375) 880-8576
(641) 576-2342
(951) 268-8744
Upvotes: 1
Reputation: 23144
findall()
returns a simple list of strings matching the pattern.
It has no group()
method, just omit that:
>>> print(mo)
['7', '3', '8', '3', '8', '3', '5', '7', '2', '9', '3', '7', '3', '5', '7',
'7', '0', '4', '9', '2', '4', '0', '3', '4', '4', '3', '2', '7', '5', '9',
'3', '7', '5', '8', '8', '0', '8', '5', '7', '6', '6', '4', '1', '5', '7',
'6', '2', '3', '4', '2', '9', '5', '1', '2', '6', '8', '8', '7', '4', '4']
Upvotes: 4