# Partial string matches in structural pattern matching

**URL:** <https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960>\
**Category:** Ideas\
**Created:** [July 20, 2023, 8:24am UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960 "2023-07-20T08:24:16Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![7om](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/7om/32/9115_2.png) [@7om](https://discuss.python.org/u/7om)\
**Post date:** [July 20, 2023, 8:24am UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/1 "2023-07-20T08:24:16Z")

</div>

Hi there,  
I’d love to be able to use partial string matches:

```auto
match text:
    case "prefix_" + cmd: # checking prefix
        print("got", cmd)
    case "Hello " + last_name + ", " + first_name + "!": # more complex example
        print(last_name, first_name)

```

I know the various tricks using `split()` or guards (`case s if s.startswith("prefix_")`), but this would be so much more intuitive for simple checks.

Any thoughts? Cheers! 🍻

---

<div class="post-metadata">

**Author:** ![barry-scott](https://avatars.discourse-cdn.com/v4/letter/b/e9c0ed/32.png) [@barry-scott](https://discuss.python.org/u/barry-scott)\
**Post date:** [July 20, 2023, 2:19pm UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/2 "2023-07-20T14:19:21Z")

</div>

You are asking that match becomes a parser.  
I am not sure that is the right tool for parsing or that you could define the parsing semantics for general use.

---

<div class="post-metadata">

**Author:** ![7om](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/7om/32/9115_2.png) [@7om](https://discuss.python.org/u/7om)\
**Post date:** [July 20, 2023, 2:38pm UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/3 "2023-07-20T14:38:55Z")

</div>

Coming from C/C++, I was surprised to see the structural aspect of match/case in Python (when it came out) like

```auto
match val:
    case ("a", x):
        print(x)

```

and this structural aspect gave me the idea of having something similar for strings.

---

<div class="post-metadata">

**Author:** ![AJNeufeld](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ajneufeld/32/12174_2.png) [@AJNeufeld](https://discuss.python.org/u/AJNeufeld)\
**Post date:** [July 20, 2023, 9:35pm UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/4 "2023-07-20T21:35:55Z")

</div>

Not wild about `case "Hello " + last_name + ", " + first_name + "!"`.

Using `f"{strings}"` might work better.

```auto
match text:
    case f"prefix_{cmd}":
        print("got", cmd)
    case f"Hello {last_name}, {first_name}!":
        print(last_name, first_name)

```

But this still it isn’t very precise. Can `first_name` contain a comma if there are two? This is a job for regular expressions!

```auto
match text:
    case re.compile(r"prefix_(?P<cmd>\w+)":
        print("got", cmd)
    case re.compile(r"Hello (?P<last_name>\w+), (?P<first_name>\w+)!"):
        print(last_name, first_name)

```

But that looks far too complex, and doesn’t answer whether we want `match`, `fullmatch`, or `search`.

Add regular expressions to the `f"{string}"` mini-language syntax?

```auto
match text:
    case rf"prefix_{cmd!(\w+)}":
        print("got", cmd)
    case rf"Hello {last_name!(\w+)}, {first_name!(\w+)}!":
        print(last_name, first_name)

```

---

<div class="post-metadata">

**Author:** ![Rosuav](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/rosuav/32/3429_2.png) [@Rosuav](https://discuss.python.org/u/Rosuav)\
**Post date:** [July 21, 2023, 12:30am UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/5 "2023-07-21T00:30:49Z")

</div>

> [@AJNeufeld](#):
>
> But this still it isn’t very precise. Can `first_name` contain a comma if there are two? This is a job for regular expressions!
> 
> ```auto
> match text:
> case re.compile(r"prefix_(?P<cmd>\w+)":
> print("got", cmd)
> case re.compile(r"Hello (?P<last_name>\w+), (?P<first_name>\w+)!"):
> print(last_name, first_name)
> 
> ```
> 
> But that looks far too complex, and doesn’t answer whether we want `match`, `fullmatch`, or `search`.

Yeah, and name-wise I’m not a fan of using “compile” as a matching feature. So here’s a thought. Can we make some sort of helper class called, say, `re.RegExp()`, which can be constructed with a pattern and which returns a type suitable for a match case statement?

I would also be in favour of having a similar function for sscanf.

These would actually end up being “type specializations” rather than actual type constructions. So `re.RegExp` and `sscanf` themselves would either be metatypes, or types that take parameters. Which might mean a viable spelling would be `re.Pattern["pattern-goes-here"]` but that might get in the way of type checkers.

---

<div class="post-metadata">

**Author:** ![kknechtel](https://avatars.discourse-cdn.com/v4/letter/k/e47c2d/32.png) [@kknechtel](https://discuss.python.org/u/kknechtel)\
**Post date:** [July 21, 2023, 5:01am UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/6 "2023-07-21T05:01:51Z")

</div>

Building in more special cases like this seems unpleasant. There will continue to be demands for more, and it’s not at all clear what should be special about compiled regexes - or any other class produced by the `re` standard library module - that would enable special behaviour with `match`.

I can, however, imagine a general extension: extend the `match` syntax to allow `as <NAME>` to capture the expression in a variable (necessary since it won’t necessarily already be a name), and extend the `case` syntax to accept a `from <EXPR>` clause (before any `if` clause) that can compute some other value and unpack and match _that_. Thus:

```auto
match text as t:
    case ("prefix", cmd) from t.split('_'):
        print('got', cmd)
    case (last_name, first_name) from re.match('Hello (.*?), (.*?)!', t).groups():
        print(last_name, first_name)
    case unknown: # default; equivalent to "case unknown from t"
        print("don't know what to do with", unknown)

```

I’m not very enthusiastic about this idea, but I wasn’t very enthusiastic about `match` in the first place.

---

<div class="post-metadata">

**Author:** ![Rosuav](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/rosuav/32/3429_2.png) [@Rosuav](https://discuss.python.org/u/Rosuav)\
**Post date:** [July 21, 2023, 5:43am UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/7 "2023-07-21T05:43:24Z")

</div>

> [@kknechtel](#):
>
> ```auto
> case _: # default; equivalent to "case _ as t"
> print("don't know what to do with", _)
> 
> ```

Minor quibble: `case _` does not bind to underscore, and is NOT equivalent to `case t` which does. I’m not sure what `case _ as t` would do but it should still not bind to underscore.

---

<div class="post-metadata">

**Author:** ![kknechtel](https://avatars.discourse-cdn.com/v4/letter/k/e47c2d/32.png) [@kknechtel](https://discuss.python.org/u/kknechtel)\
**Post date:** [July 21, 2023, 7:38am UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/8 "2023-07-21T07:38:09Z")

</div>

Fixed it - the comment didn’t properly, er, _match_ my own proposal anyway 😅

---

<div class="post-metadata">

**Author:** ![7om](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/7om/32/9115_2.png) [@7om](https://discuss.python.org/u/7om)\
**Post date:** [July 21, 2023, 7:55am UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/9 "2023-07-21T07:55:35Z")

</div>

I love the f-string approach!

I’m not saying that this syntax needs to cover all complex cases where a full-blown regular expressions makes sense. Let’s aim for a 80% coverage of simple but common cases (just like the list or tuple expressions in `case` can only handle simple but common cases).

And yes, matching a `"Hello Doe,, Jane"` with `f"Hello {last_name}, {first_name}"` should give a trailing comma in `last_name` IMHO.

If you want a search rather than a match, you could throw in a `{_}` at the beginning (and/or at the end if you want to eat trailing stuff).

---

<div class="post-metadata">

**Author:** ![flyinghyrax](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/flyinghyrax/32/12394_2.png) [@flyinghyrax](https://discuss.python.org/u/flyinghyrax)\
**Post date:** [July 21, 2023, 11:56am UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/10 "2023-07-21T11:56:01Z")

</div>

If any extension was made I also feel that general is better than specific. The match / case syntax already feels relatively complex.

When thinking about adding `case NAMES from EXPR`, this strikes me as adding the match statement to the match statement, if that makes sense? Since we can already do this:

```python
match EXPR:
    case NAMES:
        …

```

So even though it is perfectly general, adding ‘from’ might miss the original use case requested, which seemed to be something more like glob matching?

With regard to some of the other ideas like using f-strings: Python already had a lot of “mini languages” and I would argue against adding another one, especially if it was a subset of an existing one. Things that look the same as something else in the language but do something different and don’t support all the same uses is a design red flag.

> [@Rosuav](#):
>
> Can we make some sort of helper class called, say, `re.RegExp()`, which can be constructed with a pattern and which returns a type suitable for a match case statement?

This sounds fun! I might try to make that if I have time.

---

<div class="post-metadata">

**Author:** ![AJNeufeld](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ajneufeld/32/12174_2.png) [@AJNeufeld](https://discuss.python.org/u/AJNeufeld)\
**Post date:** [July 21, 2023, 2:21pm UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/11 "2023-07-21T14:21:27Z")

</div>

I don’t think `match expression as <NAME>` is necessary, since we’ve got the walrus, which can bind the expression to a variable.

```python
match (t:= some + expression):
   case ("prefix", cmd) from t.split('_'):
      print('got', cmd)
   ...

```

In the possibly more likely case where a variable already exists, no additional capture is needed.

```python
match t:
   case ("prefix", cmd) from t.split('_'):
      print('got', cmd)
   ...

```

So really, we just need the `from EXPR:` extension for `case`.

---

<div class="post-metadata">

**Author:** ![7om](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/7om/32/9115_2.png) [@7om](https://discuss.python.org/u/7om)\
**Post date:** [July 21, 2023, 3:06pm UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/12 "2023-07-21T15:06:32Z")

</div>

Structural pattern matching in Python comes with a bunch of [patterns](https://peps.python.org/pep-0634/#patterns). My idea would be to add a very simple and basic pattern to decompose strings without the need for full-blown REs.

While I enjoy the brainstorming part about making it more general, I really like the “keep it simple, cover the basics” aspect about my initial proposal. But then again, I might be biased. 😜

---

<div class="post-metadata">

**Author:** ![davidism](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/davidism/32/3295_2.png) [@davidism](https://discuss.python.org/u/davidism)\
**Post date:** [July 21, 2023, 3:08pm UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/13 "2023-07-21T15:08:19Z")

</div>

If you have a proposal, then you need to make a proposal. See how other PEPs are written to see what level of effort you need to put in. Otherwise, this Idea thread is just going to continue to be undirected speculation. Right now you’ve asked for “any thoughts” and that’s what you’re getting.

---

<div class="post-metadata">

**Author:** ![7om](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/7om/32/9115_2.png) [@7om](https://discuss.python.org/u/7om)\
**Post date:** [July 21, 2023, 3:15pm UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/14 "2023-07-21T15:15:52Z")

</div>

Don’t get me wrong, I’m not complaining (quite the opposite: “enjoy the brainstorming”), so thanks to all of you for your input. ❤

---

<div class="post-metadata">

**Author:** ![AJNeufeld](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ajneufeld/32/12174_2.png) [@AJNeufeld](https://discuss.python.org/u/AJNeufeld)\
**Post date:** [July 21, 2023, 3:21pm UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/15 "2023-07-21T15:21:59Z")

</div>

> When thinking about adding `case NAMES from EXPR`, this strikes me as adding the match statement to the match statement, if that makes sense?

The issue with the original example’s suggestion is there is way too much variability in the case handling. Implementing the desired behaviour with an `if...elif...` ladder and regular expressions is pretty clear and straightforward:

```python
import re

def test(text):
    if m := re.fullmatch("prefix_(.*?)", text):
        cmd, = m.groups()
        print("got", cmd)
    elif m := re.fullmatch("Hello (.*?), (.*?)!", text):
        last_name, first_name = m.groups()
        print(last_name, first_name)
    else:
        print(f"Don't know what to do with {text}")
        
test("prefix_Order66")
test("Hello Phol, Tom!")
test("foo bar")

```

Unlike a `match` statement, this will blow up if passed a non-string, like `test(100)`.

Otherwise, this looks kinda like a match statement, if `f"{var}"` in a `case` was matched by `(.*?)`.

```python
def test(text):
    match text:
        case f"prefix_{cmd}":
            print("got", cmd)
        case f"Hello {last_name}, {first_name}!":
            print(last_name, first_name)
        case _:
            print(f"Don't know what to do with {text}")

```

Except … interpolation of `f"prefix_{cmd}"` doesn’t require `cmd` to be an string; it could be a integer!

```python
match text:
    case f"prefix_{cmd:d}":
        print("Integer command", cmd):
    case f"prefix_{cmd:f}":
        print("Fractional command", cmd)
    case f"prefix_{cmd}":
        print("Vanilla string command", cmd)

```

But this open a whole new can of worms, which we probably don’t want to head down. For example, could `prefix_(1+1j)` be matched by `case f"prefix_{cmd!r}"` and assign `cmd = 1 + 1j`???

---

<div class="post-metadata">

**Author:** ![flyinghyrax](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/flyinghyrax/32/12394_2.png) [@flyinghyrax](https://discuss.python.org/u/flyinghyrax)\
**Post date:** [July 21, 2023, 3:40pm UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/16 "2023-07-21T15:40:48Z")

</div>

I guess my instinct here is that if one is trying to handle text with a match such that the cases are different patterns (vs one pattern and the cases are on the _regex group contents_), this isn’t “structural” pattern matching anymore. Pattern matching on strings is parsing, and I would parse the text into objects then use match on the structure of the objects.

That’s not an actual rebuttal of the proposed idea, since it reduces down to “lol y do u want to do that”, but I think it’s why I’m not enthusiastic about it. Most of the proposed uses are things where above a certain scale I’d be tokenizing input and using a PEG / parser combinator library - but ultimately that’s just a personal bias.

The existing pattern types do handle list elements though, and being able to match on substrings does feel like a natural extension of that.

---

<div class="post-metadata">

**Author:** ![7om](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/7om/32/9115_2.png) [@7om](https://discuss.python.org/u/7om)\
**Post date:** [July 21, 2023, 3:47pm UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/17 "2023-07-21T15:47:32Z")

</div>

> [@flyinghyrax](#):
>
> The existing pattern types do handle list elements though, and being able to match on substrings does feel like a natural extension of that.

That’s _exactly_ where I’m coming from, mate. 😃

---

<div class="post-metadata">

**Author:** ![flyinghyrax](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/flyinghyrax/32/12394_2.png) [@flyinghyrax](https://discuss.python.org/u/flyinghyrax)\
**Post date:** [July 22, 2023, 2:00am UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/18 "2023-07-22T02:00:10Z")

</div>

> [@flyinghyrax](#):
>
> > [@Rosuav](#):
> >
> > Can we make some sort of helper class called, say, `re.RegExp()`, which can be constructed with a pattern and which returns a type suitable for a match case statement?
> 
> This sounds fun! I might try to make that if I have time.

…juuuust kidding, took a look at the Structural Pattern Matching PEP and with the way Class patterns currently work this seems more difficult than I first thought.

---

<div class="post-metadata">

**Author:** ![mimre25](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mimre25/32/12089_2.png) [@mimre25](https://discuss.python.org/u/mimre25)\
**Post date:** [August 5, 2023, 12:31pm UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/19 "2023-08-05T12:31:37Z")

</div>

I also stumbled upon the problem of partial string matching before and tried all kind of workaround but unfortunately they all seem a bit tedious/overly complex.

I definitely like the f-string approach that was suggested earlier on and would support the addition of to improve the `match` statement. 👍

---

<div class="post-metadata">

**Author:** ![ayorgo](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ayorgo/32/30923_2.png) [@ayorgo](https://discuss.python.org/u/ayorgo)\
**Post date:** [September 15, 2025, 11:34am UTC](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960/20 "2025-09-15T11:34:43Z")

</div>

Why not just do something like this:

```python
s = "Hello Doe, Jane!"
found = re.findall(r"Hello (\w+), (\w+)!", s)
match found:
    case [(last_name, first_name)]:
        print(f"Goodbye, {first_name} {last_name}!")
    case _:
        print("Zzz...")

```

Then you can use any regex you want without having to hard-code some very special subset of it into the language.

Besides, _structural_ pattern matching is aimed at parsing, well, _structures_ that the language understands whereas strings are inherently _unstructured_. So in order to use _structural_ pattern matching on _unstructured_ input we need to _structure_ the input first which is what regexes are for in this case.

[Next page](https://discuss.python.org/t/partial-string-matches-in-structural-pattern-matching/29960.md?page=2)
