簡體   English   中英

如何使用或不使用正則表達式獲取兩個大括號之間的所有內容

[英]How to get all the contents between two curly braces with or without using regex

我有以下代碼段:

function test(){
   try {
   ---------------some contents-------
       }
   catch(e){
           }
}

現在,我想要第一對花括號之間的代碼。 輸出應該是這樣的:

   try {
   ---------------some contents-------
       }
   catch(e){
           }

使用或不使用正則表達式如何做到這一點? 我嘗試使用以下正則表達式:

Pattern p = Pattern.compile("\\{([^}]*)\\}");
        Matcher m = p.matcher(s); // s contains each line of the above text
        while (m.find()) {
        System.out.println(m.group(1));
        }

但是,它僅在單行或不存在多行大括號時才獲取內容。

你本來可以搜索得更好

使用substrindexOf / lastIndexOf

 function test(){ try { /*---------------some contents-------*/ } catch(e) {} } var testStr = String(test); testStr = testStr.substr(testStr.indexOf('{') + 1); document.querySelector('#result').textContent = testStr.substr(0, testStr.lastIndexOf('}'));
 <pre id="result"></pre>

就試一試吧:

String s = "function test(){"
        + "try {"
        + "---------------some contents-------"
        + "}"
        + "catch(e){"
        + "}"
        + "}";
int bracketStartIndex = s.indexOf("{");
System.out.println("START INDEX = " + bracketStartIndex);
int bracketEndIndex = s.lastIndexOf("}");
System.out.println("END INDEX = " + bracketEndIndex);
System.out.println("OUTPUT STRING : " + s.substring(bracketStartIndex, bracketEndIndex));

暫無
暫無

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

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