This RegEx : {=tokenstring[^{}]*(?:{[^{}]*}[^{}]*)*}/g
matches this string properly:
{=tokenstring?param1=11¶m2={token-identifier}¶m3={token-child-identifier}¶m4=20}
(That string is a token which is being used in my website. It's value changes dynamically based on the provided request data in the content pages.)
I would like to add one more condition to the RegEx. For example "param3", to find if it exists or not in the string.
I know this new RegEx: /param3=([^&])/
will get the word "param3" from the string but how to fit that new RegEx into the original RegEx?
A tentative experiment with an online debugger. Before:
{=tokenstring[^{}]*(?:{[^{}]*}[^{}]*)*}
After:
{=tokenstring[^{}]*(?:{[^{}]*}[^{}]*)*param3=(?:{[^{}]*}[^{}]*)*}
If you don't have a fixed number of parameters, it means you can't write a single regex, since you can't create regular expression with dynamic number of groups. However, you can iterate over matches. For example in PHP it would look like this
#Check if token is right
if (preg_match('/\A\{=tokenstring\?param.+\}\Z/s', $subject)) {
# Successful match. Now iterate over tokens and their params
preg_match_all('/(param\d+)=(.+?)(?:&|(?:\}$))/s', $subject, $result, PREG_SET_ORDER);
for ($matchi = 0; $matchi < count($result); $matchi++) {
$param = $result[$matchi][0];
$param_value = $result[$matchi][1];
}
} else {
# Match attempt failed
}
UPDATE: The best I could do with a single regex is the case when one parameter could be missing (that is, there're 3 or 4 parameters)
{=tokenstring\?(?:(param\d+)=(.+?)(?:&|(?:}$)))(?:(param\d+)=(.+?)(?:&|(?:}$)))(?:(param\d+)=(.+?)(?:&|(?:}$)))|(?:(param\d+)=(.+?)(?:&|(?:}$)))
You'll get matched parameters into match groups so you could detect which parameters are missing. Also the order of parameters doesn't matter.
There's also an if-then-else (?(?=condition)then|else)
construct in regex, but if you can have from 1 to 4 parameters, it means you'll have to write a nested regex of three levels, the top one checking for existence of 4 parameters, another one inside the existence of 3 parameters etc, each repeating itself with an insane number of capturing groups.