簡體   English   中英

在側花括號中獲取字符串,在其中的花括號中也有更多值

[英]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));
}

IDEONE 演示

(?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.

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