You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python单元测试中断言正则表达式模式匹配指定次数?

断言正则表达式在多行字符串中恰好匹配3次

我编写了一个Python单元测试,用于断言某正则表达式模式出现在多行字符串中,代码如下:

import unittest

class TestStrRegex(unittest.TestCase):

    def test_pattern_matches_thrice(self):
        string = """\
        repeatedval=78
        badval=89
        # comment
        repeatedval=20
        repeatedval=8978
        """
        self.assertRegex(string, 'repeatedval=\d+')

我希望断言repeatedval=\d+模式在该字符串中恰好匹配3次,尝试过如下写法但无效:

self.assertRegex(string, 'repeatedval=\d+', exact_number_of_matches=3)

请问是否有其他方法实现该断言?


解决方案

方法1:直接统计匹配结果数量

用re.findall获取所有匹配的结果,再断言结果的长度等于目标次数:

import re
import unittest

class TestStrRegex(unittest.TestCase):

    def test_pattern_matches_thrice(self):
        string = """\
        repeatedval=78
        badval=89
        # comment
        repeatedval=20
        repeatedval=8978
        """
        matches = re.findall(r'repeatedval=\d+', string)
        self.assertEqual(len(matches), 3)

方法2:自定义可复用的断言方法

如果多个测试用例都需要这类断言,可以封装成自定义方法:

import re
import unittest

class BaseTest(unittest.TestCase):
    def assertRegexMatchCount(self, target_str, pattern, expected_count):
        matches = re.findall(pattern, target_str)
        self.assertEqual(
            len(matches),
            expected_count,
            f"预期匹配{expected_count}次,实际匹配{len(matches)}次"
        )

class TestStrRegex(BaseTest):

    def test_pattern_matches_thrice(self):
        string = """\
        repeatedval=78
        badval=89
        # comment
        repeatedval=20
        repeatedval=8978
        """
        self.assertRegexMatchCount(string, r'repeatedval=\d+', 3)

额外提示

  • 正则建议用原始字符串(r''),避免转义字符冲突;
  • 如果需要严格匹配整行(比如排除repeatedval=123abc这类部分匹配),可以添加行锚点并启用多行模式:
    matches = re.findall(r'^repeatedval=\d+$', string, flags=re.MULTILINE)
    

内容的提问来源于stack exchange,提问作者nezzer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 18:48:10