0

How can I extract parts of (multi-line) inline-if that was written in javascript code like this one:

 ( MYDATA.FIELD > 1.03 ? 'higher than' : ( 0.97 > MYDATA.FIELD ? 'lower than' : 'equal to' ))+

 groups:

 "MYDATA.FIELD > 1.03" ,
 "'higher than'" ,
 "0.97 > MYDATA.FIELD" ,
 "'lower than'" ,
 "'equal to'"

for two inline-if in one line, i had this regex:

\((.*?)\s?\?(.*?)\:\s*(\((.*?)\s?\?(.*?)\:(.*?)\))\s?\)

or

 ( Condition1 == true || condition2 == 0.2 ) ?
  {"type":"text","value":"..."},
  {"type":"text","value":"..."},
  {"type":"text","value":"..."},
  :
  {"type":"text","value":"..."},
  {"type":"text","value":"..."},
 ) + ...

 groups:
 "Condition1 == true || condition2 == 0.2" ,

 "{"type":"text","value":"..."},
 {"type":"text","value":"..."},
 {"type":"text","value":"..."}," ,

 "{"type":"text","value":"..."},
 {"type":"text","value":"..."}," ,

I'm going to edit my javascript code and make json objects, so no replace function in javascript needed!

Maximum depth: 2

MohaMad
  • 2,575
  • 2
  • 14
  • 26

1 Answers1

0

My question about parsing or extracting items of inline-if or Conditional (ternary) Operator is done by this regex and story!

First, I've done in pcre(PHP) regex tester, because usages of IF-Clause in Regex or Conditional Capturing Groups or any thing you names, but known as (?(-1)true|false)

Thanks to Regex101 and it's brief definition:

(?(1)yes|no)

If capturing group 1 was matched so far, matches the pattern before the vertical bar. Otherwise, matches the pattern after the vertical bar. A group name, or a relative position (-1) in PCRE, can be used. Global flag breaks conditionals.

By this Regex 3 parts of inline If extracting: (enters and spaces are for better readability)

\(\s*
(.+?)\s*\?\s*
    (\(\s*)? (?(-1)(.+?)\s*\)|(.+?))
    \s*\:\s*
    (\(\s*)? (?(-1)(.+?)\s*\)|(.+?))
\s*\)

Demo for Above Code and Improvements in next update :

  • For multi line accepting I changed . to [^\X] because pcre do not accepts usage of [^] ...

  • Capturing groups where different in nested inline-ifs, but it was not matter!


Now back home! but, what's JavaScript IF-Clause in Regex?

Converting (\(\s*)? (?(-1)(.+?)\s*\)|(.+?)) to JavaScript Regex pattern is done by two usage of negative and positive looks: (thanks to existing Answer and others)

((?=conditional-pattern)yes-pattern|(?!conditional-pattern)no-pattern)

      ( (?=\(\s*) .+?\) | (?!\(\s*) .+? )
Condition^^^^^^^  ^^^true           ^^^false

Final regex for extracting inline-if is: (enters and spaces are for better readability)

\(\s*
([^]+?)\s*\?\s*
    ((?=\(\s*)[^]+?\)|(?!\(\s*)[^]+?)
        \s+\:\s+
    ((?=\(\s*)[^]+?\)|(?!\(\s*)[^]+?)
\s*\)
  • thanks to {"type":"text","value":"..."}, that has not : and usage of \s+\:\s+ solves my multi line search through json object definitions and finding false part.

Demo for Final Answer

Community
  • 1
  • 1
MohaMad
  • 2,575
  • 2
  • 14
  • 26