Home > Back-end >  Is there a way to use a regex inside a python pattern match?
Is there a way to use a regex inside a python pattern match?

Time:04-07

This is common across functional languages that support pattern matching, so my intuition wants this to be possible.

I am looking for something like:

match string:
    case "[a-zA-Z]":
        ... do something 
    case _:
         print("Not a match")

Even if there isn't a direct way to do this, is there any reasonable syntax for accomplishing the same goal?

CodePudding user response:

Python's re module does regex, so you can use if-elif-else:

import re
string = "test_string"
if re.match("[a-zA-Z]", string):
    # string starts with a letter
elif re.match("[0-9]", string):
    # string starts with a digit
else:
    # string starts with something else

CodePudding user response:

This means you have the possible patterns in two places... but it's as close to the spirit of the question as I can think of at the moment.

import re

test = 'hello'

patterns = ['(h)', '(e)', '(ll)', '(ello)']

for pattern in patterns:
  matches = re.search(pattern, test)
  if matches:
    match pattern:
      case '(h)':
        print('matched (h)')
        # break # add a break after each case if you want to stop after a match is found.
      case '(e)':
        print('matched (e)')
      ...etc
  • Related