views:

105

answers:

4

Hi i have a string like this:

adfsdf dsf  {{sadfsdfadf {{Infobox}} musical}} jljlk }}

i want eliminate all substring {{..}} and so i tried with

\{\{.*\}\}

this eliminates {{sadfsdfadf{{Infobox}} musical}} jljlk }} but i want eliminate {{sadfsdfadf {{Infobox}} musical}} checking the }} more near from the start of the substring

How can i do?

+3  A: 

Use a lazy quantifier:

\{\{.*?\}\}
Lucero
This is no good: in the original example, it will only go up to the brackets just after "Infobox", leaving "musical}}" when it shouldn't.
Platinum Azure
You can keep running this until the string stops changing...
kejadlen
You can keep running this all you want, and it'll never do what the poster wants. As you would instantly see if you tried it even once.
glenn mcdonald
@glenn, the example posted by Luca has changed since I posted my answer. What he not wants will only work with Regex engines supporting some kind of recursion, such as the .NET Regex or the PHP preges AFAIR.
Lucero
+1  A: 

Here's a fairly non-robust expression \{\{[a-zA-Z\s]*\}\} that will work.

confusedGeek
+1  A: 

In the general case, this won't be possible with regular expressions. You cannot match balanced parentheses, or anything like that, with a regular expression-- you need a context-free grammar instead.

That said, Perl has some facilities for recursive regular expressions; these would allow you to do what you want. I do not know if Ruby is capable of doing the same thing.

Platinum Azure
+1  A: 

Here is a quick example using a recent 1.9.x Ruby version. If you run an 1.8.x release you'll need the oniguruma gem. This doesn't take into account escaped \{\{ but does handle single { and } which I assume you will want to ignore.

#!/usr/bin/evn ruby
# Old 1.8.x versions of Ruby you'll need the gem.
# require 'oniguruma'
require 'pp'

squiggly = %r/
  (
    (?<squiggly>         # squiggly named group
      \{\{               # start {{
        (?:              # non matching group
          [^{}]          # anything not { or }
          | \{[^{]       # any { not followed by {
          | \}[^}]       # any } not followed by }
          | \g<squiggly> # nested squiggly
        )*               # zero or more times
      \}\}               # end }}
    )                    # end of squiggly
  )/x

string = 'adfsdf dsf  {{sadfsdfadf {{Infobox}} musical}} jljlk }}'
pp squiggly.match(string)[:squiggly] #=> {{sadfsdfadf {{Infobox}} musical}}
shanna
Nice one! I *thought* I'd heard Oniguruma had recursive matching. Are there any good English-language docs for it out there? The standard feature list dissolves into gibberish just when it's starting to get interesting: http://www.geocities.jp/kosako3/oniguruma/doc/RE.txt :-/
Alan Moore
Sorry, everything I know about oniguruma I picked up from that page or in practice.
shanna