0

I am not getting expected results. Anyone pl check my code below and help

Expected result:

['(444)333-4444', '444-555-3424']

Actual result:

[('(444)333-4444', '(444)', '', '333', '-', '4444', '', '', ''), ('444-555-3424', '444', '-', '555', '-', '3424', '', '', '')]

Code:

tell_op = re.compile(r'''(
    (\d{3}|\(\d{3}\))?                # area code
    (\s|-|\.)?                        # separator
    (\d{3})                           # first 3 digits
    (\s|-|\.)                         # separator
    (\d{4})                           # last 4 digits
    (\s*(ext|x|ext.)\s*(\d{2,5}))?    # extension
    )''', re.VERBOSE)
oo = tell_op.findall('this is my phone number (444)333-4444, 444-555-3424')
print(oo)
djsoteric
  • 188
  • 1
  • 10
Junaid
  • 13
  • 7
  • have you seen https://stackoverflow.com/questions/3868753/find-phone-numbers-in-python-script – Boris Verkhovskiy Dec 30 '19 at 05:27
  • 1
    Your pattern could match more than the 2 examples and re.findall will return all the capturing groups, that is why you get those results. If you change the capturing groups into non capturing ones `(?:` you have your results. If that does not match all your requirements, could you update the question with examples that you do and do not want to match? – The fourth bird Dec 30 '19 at 10:36

1 Answers1

0

please try below regex,it works for both inputs

mbl1='(444)333-4444'
mbl1='444-555-3424'

print(re.search(r'\d*\(*\d+\)*\d+\-\d+-*\d*',mbl1).group())

If you have another requirement,please let me know

SRG
  • 345
  • 1
  • 9
  • Thanks SGR, but it is not working for me however I tried: re.compile(r'(\+?\(?\d{3}\)?[-.]?\d{3}?[-.]\d{4})') it is working fine except '?' doesn't work with '\d' for pattern like 333-4444 (means with less digits) – Junaid Dec 30 '19 at 08:04
  • 1
    This regex is matching `1234567890123(((((((((((00-1----------------------`, not sure it's a valid phone number. – Toto Dec 30 '19 at 11:10
  • hey bro thanks.. i could achieve results with re.compile(r'(\+?\(?\d{2}\)?[-.\s]?\d{10}|\d{10})')... also in first code I shared I was helped by friend here, he told me to use non-capturing groups.. that also worked.. thanks a lot for your time. – Junaid Dec 30 '19 at 12:22