Alex Alex - 1 month ago 11
PHP Question

RegEx: Match LaTeX-like function with optional parameters

I want to match something like a LaTeX function with optional parameters in PHP.

Following examples should match the pattern:

example{arg0}
example{arg0}{opt1}
example{arg0}{opt1}{opt2}
example{arg0}{opt1}{opt2}{opt3}


As you can see first parameter is required but following parameters (opt1-3) are optional.

I got this one:

/example\{(.*)\}(\{(.*)\})?(\{(.*)\})?(\{(.*)\})?/U


But it's only matching the first parameters (see regex101).

What RegEx will recognize each line as match and parameters opt1-3 as groups?

Answer

You can remove the /U greediness switching modifier and replace all .* with [^{}]*:

'~example(?:\{([^{}]*)\})?(?:\{([^{}]*)\})?(?:\{([^{}]*)\})?(?:\{([^{}]*)\})?~'

See the regex demo

Details:

  • example - a string example
  • (?:\{([^{}]*)\})? - an optional group matching a {, then capturing zero or more characters other than { and }, then matching }
  • (?:\{([^{}]*)\})?(?:\{([^{}]*)\})?(?:\{([^{}]*)\})? - ibid. (3 more repetitions of the subpattern above)

PHP demo:

$re = '~example(?:\{([^{}]*)\})?(?:\{([^{}]*)\})?(?:\{([^{}]*)\})?(?:\{([^{}]*)\})?~';
$str = 'example{arg0}
example{arg0}{opt1}
example{arg0}{opt1}{opt2}
example{arg0}{opt1}{opt2}{opt3}';
preg_match_all($re, $str, $matches);
print_r($matches);