本文共 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/