返回None的正则表达式(python)

2024-06-26 14:34:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python只学了一个月,这个基本的练习让我非常兴奋。我正在尝试做一个搜索脚本,将搜索我输入的文本,并将结果放在我的剪贴板上。我被困在下面大约一个星期了。如果我直接从一个站点复制文本并输入它,没有结果(我得到一个None输出)。但如果我直接把号码抄进去,没问题,它读起来很完美。我试过好几种方法(如下所示),但没有运气,它有我难住了。下面是我粘贴的示例文本,但没有结果:

‌某人垃圾邮件博士

房间:BLD-2001

+353(0)11 123456

任何人能提供的意见都会很好。另外一个附带的问题是,任何关于学习python的书籍/建议都会令人惊叹。目前正在关注“用python自动化无聊的东西”。只是为了好玩。提前谢谢。在

import re, pyperclip

def findphone(numbers):
    numregex = re.compile(r'\(\d\)\d\d\s\d+')
    numregex1 = re.compile(r'(0)11 123456')
    phoneRegex = re.compile(r'''(
    (\+\d{3})?                    # area code
    (\s|-|\.)?                    # separator
    (\d{3}|\(\d\)\d\d)?           # area code
    (\s|-|\.)?                    # separator
    \d{6}                         # Landline Number 
    )''', re.VERBOSE)
    mo = numregex.search(numbers)
    mo0 = numregex1.search(numbers)
    mo1 = phoneRegex.search(numbers)
    print('mo ' +str(mo))
    print('mo0 ' +str(mo0))
    print('mo1 ' +str(mo1))

print('Input check text')
numbers = input()
findphone(numbers)

Tags: 文本researchareamoprintcompilenumbers
1条回答
网友
1楼 · 发布于 2024-06-26 14:34:07

查看联机更改

# -*- coding: utf-8 -*-
# 1. added above line
import re

def findphone(numbers):
    numregex = re.compile(r'(\(\d\)\d\d\s\d+)') # 2. Added circular brackets around the regular expression
    numregex1 = re.compile(r'(\(0\)11 123456)') # 3. Escaped circular brackets around 0

    # 4. Made small changes to the following, mainly changing brackets.
    phoneRegex = re.compile(r'''
    (\+\d{3})                    # area code
    [\s|-|\.]                     # separator
    (\d{3}|\(\d\)\d\d)?           # area code
    [\s|-|\.]                     # separator
    (\d{6})                         # Landline Number 
    ''', re.VERBOSE)
    mo = numregex.search(numbers)
    mo0 = numregex1.search(numbers)
    mo1 = phoneRegex.search(numbers)
    if mo:
      print('mo ' +str(mo.groups()))
    if mo0:
      print('mo0 ' +str(mo0.groups()))
    if mo1:
      # 5. break down in separate variables
      country_code = mo1.groups()[0]
      area_code = mo1.groups()[1]
      landline = mo1.groups()[2]
      print country_code, area_code, landline

print('Input check text')
findphone("‌Dr. Someone Spam\nRoom: BLD-2001\n+353 (0)11 123456")

相关问题 更多 >