1

Why does (.*?) group in /({\/\* )?#if (.*?)( \*\/})?/ not capture process.env.MODE === "std" when using {/* #if process.env.MODE === "std" */} as input?

I am aware removing ? from last group works… that said, it is a requirement.

Is it possible to work around this?

sunknudsen
  • 6,356
  • 3
  • 39
  • 76

2 Answers2

2

If you need to have an optional pattern at the end after an optional pattern (like .*?), you can convert the .*? lazy dot pattern into a tempered greedy token:

({\/\* )?#if ((?:(?! \*\/}).)*)( \*\/})?

See the regex demo.

The .*? is changed into a pattern that matches any char, zero or more but as many as possible occurrences, that is not a starting point of the */} char sequence.

Details:

  • ({\/\* )? - an optional Group 1: /* and space
  • #if - an #if string
  • ((?:(?! \*\/}).)*) - Group 2: any char other than line break chars, zero or more but as many as possible occurrences, that is not a starting point of the */} char sequence
  • ( \*\/})? - an optional Group 3: */} string
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

remove the optional '?' from the end of the regex which is making the last group optional

it should be

({\/\* )?#if (.*?)( \*\/})
Ahmed Gaafer
  • 1,603
  • 9
  • 26