3

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.

2
  • I agree that there are easier ways to do this! But, +1 for a good clear question. Commented Aug 29, 2014 at 21:30
  • 1
    Try using non-greedy quantifiers. Since else is optional, the greedy quantifier is going past it. Commented Aug 29, 2014 at 21:30

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.