-1

I want to find all if and if's condition For example: For this code:

if (bla === 3) {
}
if ((((ol === 1 || (true))))) {}
if ((1 === 4)
(this === 9)) {}

I want to get:

if (bla === 3)
if ((((ol === 1 || (true)))))
if ((1 === 4)
(this === 9))

I can make regex that find if, but my method have a problems: wrong work with a brakets(return "if ((some == some)", unclosed braket) or exits if and select unnecessary code.

XpomIX
  • 1
  • 1
  • 1
    You won't be able to do this in the general case using only native javascript RegExp, because matching nested parentheses requires a [more general parser](https://stackoverflow.com/a/56529581/21146235). If you can live with a limited number of nested parens then [you can construct a pattern](https://stackoverflow.com/a/47484553/21146235) but it won't be particularly pretty. – motto Mar 14 '23 at 21:54
  • @motto, you are assuming that the regex needs to test whether the parentheses are balanced, but the OP has not given that as a requirement. It could be known that the parentheses are balanced. – Cary Swoveland Mar 15 '23 at 00:03

2 Answers2

0

Assuming you are confident that the parentheses and braces are balanced, so that needn't be tested, and that 'if' always appears at the beginning of the string, you could match the following regular expression.

^if +\([^{]*\)(?= *\{)

Demo

This expression can be broken down as follows.

^          match beginning of string
if +\(     match 'if', then one or more spaces, then '('  
[^{]*      match zero or more characters other than '{'
\)         match ')'
(?= *\{)   positive lookahead asserts that match is followed by zero
           or more spaces followed by '{'  
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

Assuming the code syntax is always correct, there is always a { behind the if statement.

if [^{]+?(?={)

It will match the keyword if, a space after if to make sure its if keyword instead of some word starts with if, anything isnt { and followed by a {

  • if : match keyword if followed by a space
  • [^{]+?: match anything except for { and match as few as possible (+?)
  • (?={): possitive lookahead { to make sure match end with a {

Regex101 example

If you dont want inline match (something like else if (condition) {}), considering add a start anchor ^ at the beginning of the regex!

dinhit
  • 672
  • 1
  • 17