Regex removes everything outside {}
Regex remove everything outside {} for example:
before:
|loader|1|2|3|4|5|6|7|8|9|{"data" : "some data" }
after:
{"data" : "some data" }
with @Marcelo regex it works, but not if there are other {} inside {} like here:
"|loader|1|2|3|4|5|6|7|8|9|
{'data':
[
{'data':'some data'}
],
}"
a source to share
You can do something like this in Java:
String[] tests = {
"{ in in in } out", // "{ in in in }"
"out { in in in }", // "{ in in in }"
" { in } ", // "{ in }"
"pre { in1 } between { in2 } post", // "{ in1 }{ in2 }"
};
for (String test : tests) {
System.out.println(test.replaceAll("(?<=^|\\})[^{]+", ""));
}
Regular expression:
(?<=^|\})[^{]+
Basically we match any string that is "outside", as defined as something that follows a literal }
, or starting at the beginning of the line ^
until it reaches the literal {
, that is, we match [^{]+
. We replace this matched "outside" string with an empty string.
see also
- regular-expressions.info/Lookarounds
-
(?<=...)
- positive lookbehind
-
Non-regex solution for nested but single top level {...}
Depending on the specification of the problem (it's not entirely clear), you can also do something like this:
var s = "pre { { { } } } post";
s = s.substring(s.indexOf("{"), s.lastIndexOf("}") + 1);
This does exactly what it says: given an arbitrary string, s
it takes its substring from the first {
to the last }
(inclusive).
a source to share