I am currently writing a regular expression which will allow me to use a basic conditional if/else system written in JavaScript. (I know there is probably easier ways to do this!)
This is the content I need to work with:
{?if language = german}Hallo!{?else}Hello!{?endif}
{?if language = german}{#greeting}{?endif}
I have written /{\?if ([^{}]+)}(.+)(?:{\?else})?(.+)?{\?endif}/g which unfortunately only matches part of this. I have been using RegExr for testing so far.
My expected output, using the output expression 1: $1\n2: $2\n3: $3\n, would be:
1: language = german
2: Hallo!
3: Hello!
1: language = german
2: {#greeting}
3:
Unfortunately, I'm getting this instead:
1: language = german
2: Hallo!{?else}Hello!
3:
1: language = german
2: {#greeting}
3:
What am I doing wrong here? I'm relatively new to writing regular expressions, so I assume there is a way, and I'm just not doing it correctly.
You first want to make the + operators non-greedy. Then instead of making the third capturing group optional, simply place that group inside of the Non-capturing group leaving the Non-capturing group optional.
/{\?if ([^{}]+)}(.+?)(?:{\?else}(.+?))?{\?endif}/g
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With