博客
关于我
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/

    你可能感兴趣的文章
    propertyPlaceholderConfigurer读取配置文件
    查看>>
    proteus三输入与非门名字_proteus 元件名称对照表
    查看>>
    Protobuf - 语法、字段使用规则、注意事项
    查看>>
    protobuf —— 快速上手
    查看>>
    protobuf —— 认识和安装
    查看>>
    Protobuf 三个关键字required、optional、repeated的理解
    查看>>
    ProtoBuf 原理详解
    查看>>
    Protobuf 实例(java)
    查看>>
    ProtoBuf 实际应用(java)
    查看>>
    Protobuf 属性解释
    查看>>
    Protobuf 编译工具转换 Java 类
    查看>>
    protobuf使用详解
    查看>>
    ProtoBuf在使用protoc进行编译时提示: Required fields are not allowed in proto3
    查看>>
    Protobuf学习 - 入门
    查看>>
    protobuf对象与JSON相互转换
    查看>>
    ProtoBuf的介绍以及在Java中使用protobuf将对象进行序列化与反序列化
    查看>>
    protocol学习笔记001---RPC和HTTP协议之间的区别_与各自优势
    查看>>
    protostuff简单应用
    查看>>
    PRover 开源项目教程
    查看>>
    PyTorch-Tutorials【pytorch官方教程中英文详解】- 4 Transforms
    查看>>