2

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?

5
  • As you use the U-flag, all your optional groups are lazy, thus don't match if they don't need to. You might make them lazy again by using (..)?? or don't use U. You could also consider using a negated character class instead of lazy .*, like [^}\n\r]* Commented Nov 4, 2016 at 15:23
  • Not using modifier U ist not working (tried that before). But doubling all the question marks did the trick! Thank you very much :) If you put it as answer I'll choose and upvote. Commented Nov 4, 2016 at 15:53
  • I were too happy too soon. Looks like it's working in PCRE but not with PHP :/ Commented Nov 4, 2016 at 15:58
  • Looks like it's working in PCRE but not with PHP - You are definitely not using the regex properly. Please share the code you are using. Commented Nov 4, 2016 at 15:59
  • @WiktorStribiżew You're right, I did some mistake changing two lines of code at same time -.- Commented Nov 4, 2016 at 16:18

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.