-2

I spent a lot of time to write a regex to match the following strings:

tel/mob: 001 433 123 4352
tel/mob: 0014331234352
tel: 001 433 123 4352
tel: 0014331234352
tel/mob: 001 (433) 123 4352
tel: 001 (433) 123 4352
tel/mob: +1 433 123 4352
tel/mob: +14331234352
tel: +1 433 123 4352
tel: +14331234352
tel/mob: +1 (433) 123 4352
tel: +1 (433) 123 4352

What I did is:

print (re.findall(r':\s(\w+)' , article))

But it does not work properly, I need to extract numbers.

Mahdi
  • 967
  • 4
  • 18
  • 34

2 Answers2

1

I've allowed an optional + sign at the start, and repeating groups of numbers, and optional parenthesis. Works on supplied examples.

r':\s\+?(\(?[0-9]+\)?\s?)+'

https://regex101.com/r/ugQU0D/1

Neil
  • 3,020
  • 4
  • 25
  • 48
  • it does not contain strings that have spaces within, like 001 433 123 4352 – Mahdi Dec 30 '19 at 11:09
  • what do you mean? – Neil Dec 30 '19 at 11:27
  • For example, for a number like 001 4331234352 it just matches 43312344352 and 001 is not match – Mahdi Dec 30 '19 at 11:32
  • @Mahdi first, it does match 001 43312352. Check in the link. Second, if you are going to ask a question about regexes you must put all the examples you want to match. I can't guess what else is in your data. – Neil Dec 30 '19 at 14:24
1

What about taking everything after the :, that is ether a digit, space, plus or bracket ?

import re

data = """tel/mob: 001 433 123 4352
tel/mob: 0014331234352
tel: 001 433 123 4352
tel: 0014331234352
tel/mob: 001 (433) 123 4352
tel: 001 (433) 123 4352
tel/mob: +1 433 123 4352
tel/mob: +14331234352
tel: +1 433 123 4352
tel: +14331234352
tel/mob: +1 (433) 123 4352
tel: +1 (433) 123 4352"""

for line in data.splitlines():
    m = re.search(r':([0-9() +]+)', line)
    print ''.join(c for c in m.groups()[0] if c.isdigit())

Output:

0014331234352
0014331234352
0014331234352
0014331234352
0014331234352
0014331234352
14331234352
14331234352
14331234352
14331234352
14331234352
14331234352

https://regex101.com/r/QYSlJj/1

Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47