Python爬虫:正则匹配网址中的数字


# 匹配网址中的数字
import re

url = "https://www.baidu.com/company/13828?param=abc"
com_id = re.match(".*company/(\d+)", url)

print com_id.group(1)
# 13828

将其封装为函数

# -*- coding: utf-8 -*-

# @File    : get_digit.py
# @Date    : 2018-05-25

# 匹配网址中的数字
import re

def get_digit(url, reg_exp=".*/(\d+)"):
    """匹配网址中的数字
    :param
        url{str}: 网址字符串
        reg_exp{str}: 正则匹配规则
    :return
        digit {None}/{str}: 空或者数字字符串
    """
    digit = None

    pattern = re.compile(reg_exp)
    result = pattern.match(url)

    if result:
        digit = result.group(1)

    return digit


if __name__ == '__main__':
    # 匹配为空
    url = ""
    ret = get_digit(url)
    print(ret)
    # None

    # 匹配一个
    url = "https://www.baidu.com/company/13828?param=abc"
    ret = get_digit(url)
    print(ret)
    # 13828

    # 匹配第一个
    url = "https://www.baidu.com/company/13828?param=234234"
    ret = get_digit(url)
    print(ret)
    # 13828

猜你喜欢

转载自blog.csdn.net/mouday/article/details/80459158