[英]Getting string in side curly braces that also has more values in curly braces within it
So here's my (java) string所以这是我的(java)字符串
String s = "Some string preceding this {\"Key1\": \"Val1\", \"Key2\": {\"embedKey1\": \"embedVal1\", \"embedKey2\": \"embedVal2\"}, \"Key3\" : \"Val3\", \"Key3\": \"Val4\"}, some value proceeding it"
I want to get everything that is within the outer curly braces.我想获得外花括号内的所有内容。 How do I do that?我怎么做? So far I've tried the following到目前为止,我已经尝试了以下
Pattern p = Pattern.compile("\\{([^}]*)\\}");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group(1));
}
This however, only prints然而,这仅打印
"Key1": "Val1", "Key2": {"embedKey1": "embedVal1", "embedKey2": "embedVal2"
Can someone please help me with this?有人可以帮我解决这个问题吗?
To get everything in between outer braces, or between the first {
and the last }
, use greedy matching with a .
要获取外大括号之间或第一个{
和最后一个}
之间的所有内容,请使用带有 a 的贪婪匹配.
matching all symbols (with DOTALL mode):匹配所有符号(使用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));
}
See IDEONE demo看IDEONE 演示
The (?s)
is an inline version of the Pattern.DOTALL
modifier. (?s)
是Pattern.DOTALL
修饰符的内联版本。
For your particular example you can use a regex like this:对于您的特定示例,您可以使用这样的正则表达式:
\{(.*?)\{.*?}(.*?)}
Match information匹配信息
MATCH 1
1. [40-64] `"Key1": "Val1", "Key2": `
2. [116-149] `, "Key3" : "Val3", "Key3": "Val4"`
On the other hand, if you want to even capture the inner curly braces you can use something easier like this:另一方面,如果您甚至想捕获内部花括号,您可以使用以下更简单的方法:
\{(.*)}
Match information匹配信息
MATCH 1
1. [40-149] `"Key1": "Val1", "Key2": {"embedKey1": "embedVal1", "embedKey2": "embedVal2"}, "Key3" : "Val3", "Key3": "Val4"`
QUICK REFERENCE
Remember to escape backslashes in java:记住在java中转义反斜杠:
Pattern p = Pattern.compile("\\{(.*)}");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group(1));
}
If It's just about outermost "{" and "}" as you mentioned in your problem, this may be one of the non-regex approach.如果它只是您在问题中提到的最外面的“{”和“}”,这可能是非正则表达式方法之一。
int first=s.indexOf('{');
int last=s.lastIndexOf('}');
String result=s.substring(first, last+1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.