Matching if / else with regex
I am currently writing a regular expression that will allow me to use a basic if / else conditional system written in JavaScript. (I know there might be 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 wrote /{\?if ([^{}]+)}(.+)(?:{\?else})?(.+)?{\?endif}/g
which unfortunately only matches part of this. I have been using RegExr for testing so far.
My expected result using an 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 get 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 regex, so I'm guessing there is a way, and I'm just not doing it right.
source to share
First you want to make the statements +
non-greedy . Then, instead of making the third capturing group optional, just put that group inside a non-capturing group, and then the non-capturing group is optional.
/{\?if ([^{}]+)}(.+?)(?:{\?else}(.+?))?{\?endif}/g
source to share