如何在 js 中使用正则表达式查找所有 ifs 和 ifs 的条件

问题描述 投票:0回答:2

我想找到所有if和if的条件 例如: 对于此代码:

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

我想得到:

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

我可以使正则表达式找到是否,但我的方法有一个问题:错误的 brakets 工作(返回“if((some == some)”,unclosed braket)或退出 if 并选择不必要的代码。

javascript regex
2个回答
0
投票

假设您确信圆括号和大括号是平衡的,因此无需测试,并且

'if'
总是出现在字符串的开头,您可以匹配以下正则表达式。

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

演示

这个表达式可以分解如下

^          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 '{'  

0
投票

假设代码语法总是正确的,那么if语句后面总是有一个

{

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

它将匹配关键字

if
if
之后的空格以确保它的if关键字而不是某个单词以if开头,任何东西都不是
{
然后是
{

  • if 
    :如果后跟空格则匹配关键字
  • [^{]+?
    :匹配除
    {
    之外的任何内容,并尽可能少地匹配(
    +?
    )
  • (?={)
    :积极的前瞻
    {
    以确保比赛以
    {
  • 结束

Regex101 示例

如果你不想要内联匹配(比如

else if (condition) {}
),考虑在正则表达式的开头添加一个开始锚点
^

© www.soinside.com 2019 - 2024. All rights reserved.