博客
关于我
Python - 正则表达式在括号之间获取数字
阅读量:799 次
发布时间:2023-03-05

本文共 1358 字,大约阅读时间需要 4 分钟。

Python 正则表达式提取括号内数字的方法

在 Python 中提取字符串中的括号内数字,可以通过正则表达式来实现。以下是详细的方法和示例说明。

方法概述

要提取字符串中的括号内数字,可以使用 Python re 模块中的 re.findall 函数。通过设计一个适当的正则表达式,可以匹配括号内的数字并提取出来。

正则表达式说明

正则表达式的设计需要满足以下条件:

  • 匹配左括号 (
  • 匹配一个或多个数字 [0-9]+
  • 匹配右括号 )

因此,基础的正则表达式为:

\(([0-9]+)\)

示例代码

以下是一个完整的代码示例:

import redef get_numbers(string):    # 查找所有括号内的数字    matches = re.findall(r'\(([0-9]+)\)', string)    return matches# 测试函数def test_get_numbers():    assert get_numbers("The answer is (42), the question is what?") == ['42']    assert get_numbers("The answer is (1, 2, 3), the question IS what?") == ['1', '2', '3']    assert get_numbers("No numbers here") == []        print("All tests passed.")

使用说明

  • 导入正则表达式模块首先需要导入 re 模块:

    import re
  • 定义提取函数创建一个函数 get_numbers,接收一个字符串参数,返回括号内的数字列表:

    def get_numbers(string):    # 查找所有括号内的数字    matches = re.findall(r'\(([0-9]+)\)', string)    return matches
  • 编写测试函数编写一个测试函数 test_get_numbers,验证 get_numbers 函数的正确性:

    def test_get_numbers():    assert get_numbers("The answer is (42), the question is what?") == ['42']    assert get_numbers("The answer is (1, 2, 3), the question IS what?") == ['1', '2', '3']    assert get_numbers("No numbers here") == []    print("All tests passed.")
  • 运行测试函数调用 test_get_numbers 函数执行测试:

    test_get_numbers()
  • 扩展说明

    • 如果需要匹配多个连续的数字,可以保留 [0-9]+ 表达式。
    • 如果需要匹配带有小数点或其他字符的数字格式,可以根据具体需求调整正则表达式。

    总结

    通过以上方法,可以轻松提取字符串中的括号内数字。这种方法灵活且高效,适用于处理各种包含括号的文本数据。

    转载地址:http://csafk.baihongyu.com/

    你可能感兴趣的文章
    PyCharm快捷键
    查看>>
    Pycharm快捷键记录
    查看>>
    pycharm怎么支持WPS?
    查看>>
    pycharm打印不全问题
    查看>>
    pycharm提示This inspection detects instance attribute definition outside __init__ method
    查看>>
    pycharm搭建spark环境
    查看>>
    pycharm无法导入本地模块问题
    查看>>
    PyTorch — 初学者教程
    查看>>
    PyCharm更换pip源为国内源、模块安装、PyCharm依赖包导入导出教程
    查看>>
    Pycharm没有找到manage repositories按钮解决方案
    查看>>
    PyCharm点击设置没反应,无法进行设置
    查看>>
    pycharm的安装配置和简单使用
    查看>>
    pycharm的环境管理-ChatGPT4o作答
    查看>>
    pycharm社区版不能使用conda
    查看>>
    Pycharm终端中conda无法切换到虚拟环境的解决方法(两种方案)
    查看>>
    pycharm连接sqlite
    查看>>
    Pycharm那些隐藏的实用小技巧,yyds!
    查看>>
    PyCharm配置SSH和SFTP远程连接服务器
    查看>>
    Pycharm隐藏的实用小技巧!建议收藏
    查看>>
    PyChord 项目常见问题解决方案
    查看>>