pythonregexpython-3.10structural-pattern-matching

Structural pattern matching using regex


I have a string that I'm trying to validate against a few regex patterns and I was hoping since Pattern matching is available in 3.10, I might be able to use that instead of creating an if-else block.

Consider a string 'validateString' with possible values 1021102,1.25.32, string021.

The code I tried would be something like the following.

match validateString:
    case regex1:
        print('Matched regex1')
    case regex2:
        print('Matched regex2')
    case regex3:
        print('Matched regex3')

For regex 1, 2 and 3, I've tried string regex patterns and also re.compile objects but it doesn't seem to work.

I have been trying to find examples of this over the internet but can't seem to find any that cover regex pattern matching with the new python pattern matching.

Any ideas for how I can make it work?

Thanks!


Solution

  • It is not possible to use regex-patterns to match via structural pattern matching (at this point in time).

    From: PEP0643: structural-pattern-matching

    PEP 634: Structural Pattern Matching
    Structural pattern matching has been added in the form of a match statement and case statements of patterns with associated actions. Patterns consist of sequences, mappings, primitive data types as well as class instances. Pattern matching enables programs to extract information from complex data types, branch on the structure of data, and apply specific actions based on different forms of data. (emphasis mine)

    Nothing in this gives any hint that evoking match / search functions of the re module on the provided pattern is intended to be used for matching.


    You can find out more about the reasoning behind strucutral pattern matching by reading the actuals PEPs:

    they also include ample examples on how to use it.