Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching if/else statement with regular expression

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.

like image 223
Forest Avatar asked Aug 29 '26 21:08

Forest


1 Answers

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

like image 148
hwnd Avatar answered Sep 05 '26 10:09

hwnd