Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression problem

Tags:

regex

what's the regex for get all match about:

IF(.....);

I need to get the start and the end of the previous string: the content can be also ( and ) and then can be other (... IF (...) ....) I need ONLY content inside IF. Any idea ?

That's because, I need to get an Excel formula (if condition) and transforms it to another language (java script).

EDIT:
i tried

       `/IF\s*(\(\s*.+?\s*\))/i or /IF(\(.+?\))/`

this doesn't work because it match only if there aren't ) or ( inside 'IF(...)'

like image 650
enfix Avatar asked Jan 27 '26 06:01

enfix


1 Answers

I suspect you have a problewm that is not suitable for regex matching. You want to do unbounded counting (so you can match opening and closing parentheses) and this is more than a regexp can handle. Hand-rolling a parser to do the matching you want shouldn't be hard, though.

Essentially (pseudo-code):

Find "IF"
Ensure next character is "("
Initialise counter parendepth to 1
While parendepth > 0:
  place next character in ch
  if ch == "(":
    parendepth += 1
  if ch == ")":
    parendepth -= 1

Add in small amounts of "remember start" and "remember end" and you should be all set.

like image 91
Vatine Avatar answered Jan 28 '26 22:01

Vatine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!