[英]Getting string in side curly braces that also has more values in curly braces within it
所以這是我的(java)字符串
String s = "Some string preceding this {\"Key1\": \"Val1\", \"Key2\": {\"embedKey1\": \"embedVal1\", \"embedKey2\": \"embedVal2\"}, \"Key3\" : \"Val3\", \"Key3\": \"Val4\"}, some value proceeding it"
我想獲得外花括號內的所有內容。 我怎么做? 到目前為止,我已經嘗試了以下
Pattern p = Pattern.compile("\\{([^}]*)\\}");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group(1));
}
然而,這僅打印
"Key1": "Val1", "Key2": {"embedKey1": "embedVal1", "embedKey2": "embedVal2"
有人可以幫我解決這個問題嗎?
要獲取外大括號之間或第一個{
和最后一個}
之間的所有內容,請使用帶有 a 的貪婪匹配.
匹配所有符號(使用DOTALL模式):
String s = "Some string preceding this {\"Key1\": \"Val1\", \"Key2\": {\"embedKey1\": \"embedVal1\", \"embedKey2\": \"embedVal2\"}, \"Key3\" : \"Val3\", \"Key3\": \"Val4\"}, some value proceeding it";
Pattern p = Pattern.compile("(?s)\\{(.*)}");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group(1));
}
(?s)
是Pattern.DOTALL
修飾符的內聯版本。
對於您的特定示例,您可以使用這樣的正則表達式:
\{(.*?)\{.*?}(.*?)}
匹配信息
MATCH 1
1. [40-64] `"Key1": "Val1", "Key2": `
2. [116-149] `, "Key3" : "Val3", "Key3": "Val4"`
另一方面,如果您甚至想捕獲內部花括號,您可以使用以下更簡單的方法:
\{(.*)}
匹配信息
MATCH 1
1. [40-149] `"Key1": "Val1", "Key2": {"embedKey1": "embedVal1", "embedKey2": "embedVal2"}, "Key3" : "Val3", "Key3": "Val4"`
QUICK REFERENCE
記住在java中轉義反斜杠:
Pattern p = Pattern.compile("\\{(.*)}");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group(1));
}
如果它只是您在問題中提到的最外面的“{”和“}”,這可能是非正則表達式方法之一。
int first=s.indexOf('{');
int last=s.lastIndexOf('}');
String result=s.substring(first, last+1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.