簡體   English   中英

Javascript正則表達式或子字符串來獲取是否阻止內容?

[英]Javascript regex or substring to get if block content?

我正在尋找regex或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("}")));

描述

該例程將在括號內捕獲所需的文本,而不管嵌套如何。

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   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM