如何使用正则表达式分隔电话号码中的空格?

时间:2019-03-10 23:01:10

标签: regex python-3.x

我有3个电话号码,格式不同。

Feature.define_method(:action) { "Patch" }
# other methods follow

Base.new.action
  #=> "Patch"

我只需要查找数字,而忽略空格和括号。我需要字典中输出xxx-xxx-xxxx。

到目前为止,我已经尝试过:

(123) 456 7890

234-567-9999

345  569 2411 # notice there are two spaces after 345

3 个答案:

答案 0 :(得分:0)

问题是您要匹配电话号码的整个部分,从第一个数字开始到最后一个数字结束,包括两者之间的任何空格,破折号或括号。

要解决此问题,您应该仅匹配数字组。您可以使用捕获组并为每个数字组使用一个组(即[3]-[3]-[4]。

例如:

phone_list = []
lines = ["(123) 456 7890", "234-567-9999", "345 569 2411"]

for line in lines:
    re_match = re.search("(\d{3}).*(\d{3}).*(\d{4})", line)

    if re_match:
        formatted_number = "".join(re_match.groups())
        phone_list.append(formatted_number)

包含phone_list的结果:

['1234567890', '2345679999', '3455692411']

答案 1 :(得分:0)

您可以将re.findall用于仅与数字匹配的模式:

PhoneLst.append(''.join(re.findall(r'\d+', line)))

答案 2 :(得分:0)

这是另一个使用列表理解的答案。

import re

# List of possible phone numbers
possible_numbers = ['(123) 456 7890', '234-567-9999', '345 569 2411']

# Use list comprehension to look for phone number pattern
# numbers is a list
numbers = [n for n in possible_numbers if re.search('(\d{3}.*\d{3}.*\d{3})', n)]

# Use list comprehension to reformat the numbers based on your requirements 
# formatted_number is a list
formatted_number = [(re.sub('\s', '-', x.replace('(','').replace(')',''))) for x in numbers]

# You mentioned in your question that you needed the outout in a dictionary.
# This code will convert the formatted_number list to a dictionary.
phoneNumbersDictionary = {i : formatted_number[i] for i in range(0, len(formatted_number))}

print (phoneNumbersDictionary)
# output
{0: '123-456-7890', 1: '234-567-9999', 2: '345-569-2411'}