如何匹配“ C”,“ C ++”或“ C#”? 我有以下测试案例: cpp_csharp_regex_test_cases = [ (“ C ++”,true), (“ c#”,true), (“ C+”,false), (“ c ##”,false), (“ c&quo ...

问题描述 投票:0回答:1
我可以使用哪种正则表达方式通过pytest?我尝试了

r"^C[+{2},#{1}]$"

我尝试了Tim Biegeleisen的解决方案,但失败了:
C

	
评估您期望这些匹配是整个输入字符串,然后使用:

________________________________________________________________________________ test_cpp_csharpRegex[C-True] ________________________________________________________________________________ data = 'C', expected = True @pytest.mark.parametrize("data, expected", CPP_CSHARP_REGEX_TEST_CASES) def test_cpp_csharpRegex(data, expected): cpp_csharp_regex = r"\bC(?:\+\+|#)(?=\s|$)" > assert expected == bool(re.match(cpp_csharp_regex, data)) E AssertionError: assert True == False E + where False = bool(None) E + where None = <function match at 0x7ab4e2cded40>('\\bC(?:\\+\\+|#)(?=\\s|$)', 'C') E + where <function match at 0x7ab4e2cded40> = re.match regex_test.py:131: AssertionError ================================================================================== short test summary info =================================================================================== FAILED regex_test.py::test_cpp_csharpRegex[C-True] - AssertionError: assert True == False ================================================================================ 1 failed, 70 passed in 0.08s ================================================================================
如果您想作为较大的字符串的一部分捕获这些比赛,而匹配的匹配被白色包围,则使用:
regex python-3.12
1个回答
1
投票
^C(?:\+\+|#)$


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.