Extracting phone numbers from a free form text in python by using regex

前端 未结 4 634
遇见更好的自我
遇见更好的自我 2020-12-22 11:49

I have to extract phone numbers from free form of texts.

How can I manage it by using reg-ex in python?

I have found for one in order to extract e-mail addre

4条回答
  •  被撕碎了的回忆
    2020-12-22 12:39

    This should find all the phone numbers in a given string including international numbers. Taking the example by @buckley, Lets use the string

    text="""Matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof, like 333 4445555, (333)4445555 or 333444-5555. Does not match international notation +13334445555, but matches domestic part in +1 333 4445555."""

    re.findall(r'+?(?[1-9][0-9 .-()]{8,}[0-9]', text)

     >>> re.findall(r'[\+\(]?[1-9][0-9 .\-\(\)]{8,}[0-9]', text)
    ['3334445555', '333.444.5555', '333-444-5555', '333 444 5555', 
     '(333) 444 5555', '333 4445555', '(333)4445555', '333444-5555', 
     '+13334445555', '+1 333 4445555']
    

    Basically, the regex lays out these rules

    1. The matched string may start with + or ( symbol
    2. It has to be followed by a number between 1-9
    3. It has to end with a number between 0-9
    4. It may contain 0-9 (space) .-() in the middle.

提交回复
热议问题