views:

86

answers:

4

Regex to remove everything outside the { } for example:

before: |loader|1|2|3|4|5|6|7|8|9|{"data" : "some data" }

after: {"data" : "some data" }

with @Marcelo's regex this works but not if there are others {} inside the {} like here:

"|loader|1|2|3|4|5|6|7|8|9|
   {'data':  
       [ 
         {'data':'some data'}
       ],  
   }"
A: 

This seems to work - What language are you using - Obviously Regex... but what server side - then I can put it into a statement for you

{(.*)}
Glycerine
Don't you need to escape the `{` and `}`?
polygenelubricants
Sure, but it depends on which language its used in to attain how the complete regex will look this is devoid of flags n'all `\{(.*)\}`.
Glycerine
A: 

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 languages afaik)

Ed Woodcock
Why would you use replace to pull out a match in a String?
Yar
Works with multiple instances and automatically concatenates them? Or maybe just because I don't like C#'s Match operator (It returns an object that does stuff instead of a string). It's kind of irrelevant, this is a tiny example and this way will work just fine.
Ed Woodcock
Don't you need to escape the `{` and `}`?
polygenelubricants
@polygenelubricants Nope, not in C# (might have to in other languages).
Ed Woodcock
A: 

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("(?<=^|\\})[^{]+", ""));
    }

The regex is:

(?<=^|\})[^{]+

Basically we match any string that is "outside", as defined as something that follows a literal }, or starting from the beginning of the string ^, until it reaches a literal{, i.e. we match [^{]+, We replace these matched "outside" string with an empty string.

See also


A non-regex Javascript solution, for nestable but single top-level {...}

Depending on the problem specification (it isn't exactly 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 starting from the first { to the last } (inclusive).

polygenelubricants
A: 

Hello,

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 this will not work if "some data" has curly braces so the solution highly depends on your input data.

I hope this will help you

Jerome Wagner

Jerome WAGNER
i use string.match(/\{.*\}/,'') and it works also for curly braces inside the first
Sep O Sep