Regex to match start and middle of a string to parse Content-Type header
13:42 17 Sep 2026

I'm not good at RegEx and trying to break a string into groups where the start and optional middle are matched, and also the part before and after the optional middle is captured in a group:

https://regex101.com/r/qq0Zwq/1

This is my work-in-progress RegEx (case insensitivity is on):

^([^;]+)(;\s*charset=[a-z0-9-]*)?(.*)$

This are my test strings:

multipart/form-data; boundary=X
multipart/form-data; boundary="X"
multipart/form-data; charset=UTF-8
multipart/form-data; boundary=
multipart/form-data; foo=bar
multipart/form-data; bogus=1
multipart/form-data;boundary=X;charset=UTF-8
multipart/form-data; charset=UTF-8;   boundary=X
multipart/form-data;  boundary=X;  charset=ISO-8859-1
multipart/form-data; boundary=X; foo=bar
multipart/form-data; boundary=X; charset=UTF-8; foo=bar

It is for matching a Content-Type header. I need the Content-Type, thus the first part of the string ("multipart/form-data" in this example) in a capture group, the charset (if any) and everything else before and after the charset, if any. The problem is that .* is greedy, otherwise I could put it before the charset-matching and this could by my RegEx:

^([^;]+)(.*)(;\s*charset=[a-z0-9-]*)?(.*)$

So, taking the last example, I would want to capture in groups 1-4 the following:

  1. multipart/form-data

  2. ; boundary=X

  3. ; charset=UTF-8

  4. ; foo=bar

Is there a clever way to do this?

regex