regexpython-3.12

How to match "C", "C++" or "C#"?


I have the following test cases:

CPP_CSHARP_REGEX_TEST_CASES = [
    ("C++", True),
    ("C#", True),
    ("C+", False),
    ("C##", False),
    ("C", True),
]

Which regular expression could I use to pass pytest?


Solution

  • Assuming you expect these matches to be the entire input string, then use:

    ^C(?:\+\+|#)?$
    

    If you want to catch these matches perhaps as part of a larger string, with the matches surrounded by whitespace, then use:

    \bC(?:\+\+|#)?(?!\S)