[英]Get all strings between two curly braces using regex in javascript
[英]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));
}
但是,它僅在單行或不存在多行大括號時才獲取內容。
你本來可以搜索得更好
使用substr
和indexOf
/ 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.