Issue with regular expression output

Viewed 48

I am using the following code to filter out phone numbers from a text file.

import re

pattern = (r'\d*-\d*-\d*')
names = (r'\w*')

with open('records.txt', 'r') as f:
    for line in f:
        matches = re.findall(pattern, line)
        namesMatch = re.findall(names, line) 
        if matches:
            print(matches)
        elif namesMatch:
            print(namesMatch + ":")`

I am getting the following output:

['John']
['222-333-4447']
['423-444-5678']
['123-455-1223']
['Paul']
['423-444-5778']

I want a similar output but in string format like below:

John:
222-333-4447
423-444-5678
123-455-1223
Paul:
423-444-5778
1 Answers

You can use

import re
text = """John................. .............222-333-4447....... .. 423-444-5678 .... .................123-455-1223............... ........Paul... ......423-444-5778....................................... – 
Nithin"""
pattern=r"(\w+)((?:[\s:.]*\d+[-—–]\d+[-—–]\d+)+)"
print( [(x, " ".join(y.replace('.','').split())) for x,y in re.findall(pattern, text)] )

Output:

[('John', '222-333-4447 423-444-5678 123-455-1223'), ('Paul', '423-444-5778')]

See the Python demo.

Details:

  • (\w+) - Group 1: one or more word chars
  • ((?:[\s:.]*\d+[-—–]\d+[-—–]\d+)+) - Group 1: one or more occurrences of the following pattern sequence
    • [\s:.]* - zero or more whitespaces, colons and dots
    • \d+ - one or more digits
    • [-—–] - a hyphen or dash
    • \d+[-—–]\d+ - one or more digits, a dash, one or more digits.
Related