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'}
       ],  
   }"

      

+2


a source to share


5 answers


This seems to work. What language are you using? Obviously Regex ... but which server side - then I can put it in the instruction for you.



{(.*)}

      

0


a source


You want to do:

Regex.Replace("|loader|1|2|3|4|5|6|7|8|9|{\"data\" : \"some data\" }", ".*?({.*?}).*?", "$1");

      



(C # syntax, regex should be fine in most afaik languages)

0


a source


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


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).

0


a source


in javascript you can try

s = '|loader|1|2|3|4|5|6|7|8|9|{"data" : "some data" }';
s = s.replace(/[^{]*({[^}]*})/g,'$1');
alert(s);

      

of course it won't work if "some data" has curly braces, so the solution is highly dependent on your input.

I hope this helps you

Jerome Wagner

0


a source


For anyone looking for this for PHP, only this one worked for me:

preg_replace("/.*({.*}).*/","$1",$input);

      

0


a source







All Articles