0

我正在寻找 javascript 的正则表达式或子字符串以有效地完成以下任务。假设我的输入是

if(browser=="IE7"){
    if(check=="false"){
        ...
        console.log(something);
        console.log(something1);
        ...
         }
 }
 else {
        console.log(somethigelse);
 }

输出应该是:

if(check=="false"){
    ...
    console.log(something);
    console.log(something1);
    ...
}

我尝试过的是基本的,如下所示,它只是一个没有任何换行符的字符串。

var some="if(browser=='IE7'){console.log(IE7)}else{console.log(FF)}"
console.log(some.substring(some.indexOf("if(browser=='IE7'){")+19, some.indexOf("}")));
4

1 回答 1

0

描述

无论嵌套如何,此例程都会在括号内捕获所需的文本。

JavaScript 代码

 /*jshint multistr: true */
 var sourcestring = 'if(browser=="IE7"){ \
    if(check=="false"){ \
        ... \
        console.log(something); \
        console.log(something1); \
        ... \
         } \
 } \
 else { \
        console.log(somethigelse); \
 }';

  var i = 0;
  var splitstring = sourcestring.split(/([{}])/);
  var Output;
  var blnInside = false;
  var DepthCount = 0;
  var FoundDepth = 0;
  var DesiredRegex = /if\(browser=="IE7"\)/ig;

  for (i = 0; i < splitstring.length; i ++) {

    // if this is a close bracket, decrease the depth
    // this is first to prevent close brackets form being processed if they are the outer most bracket around the desired text
    if (splitstring[i] == "}") {
        DepthCount --;
    }

    // if you're inside and more deep then matching text then process the line
    if (blnInside && DepthCount > FoundDepth) {
        print ("line " + i + " is inside " +splitstring[i]);    
    } 

    // if this is an open bracket, then increase the depth
    if (splitstring[i] == "{") {
        DepthCount ++;
    }

    // if the current depth falls below the found depth then you are no longer inside
    if (DepthCount <= FoundDepth ) { 
        blnInside = false;
    }

    // set blnInside to true if the this has the desired text
    if (DesiredRegex.exec(splitstring[i]) && !blnInside) {
        FoundDepth = DepthCount;
        blnInside = true;
    }

}

输出

line 2 is inside      if(check=="false")
line 3 is inside {
line 4 is inside          ...         console.log(something);         console.log(something1);         ...          
line 5 is inside }
line 6 is inside   
于 2013-07-29T15:58:28.733 回答