# YBlog - Remplacer tout sauf une partie
Keywords: ruby, regexp, regular expression

Anglais ↓ Menu ↓

# Remplacer tout sauf une partie

My problem is simple:

I want to filter a text except some part of it. I can match easily the part I don’t want to be filtered. For example

    ...
    text
    ...
    BEGIN not to filter
    ...
    text
    ...
    END not to filter
    ...
    text
    ...

I searched a better way to do that, but the best I can do is using `split` and `scan`.

    def allExceptCode( f, content )
        # Beware the behaviour will change if you add
        # parenthesis (groups) to the regexp!
        regexp=/<code[^>]*>.*?<\/code>|<pre[^>]*>.*?<\/pre>/m
        tmp=""
        mem=[]
        content.scan(regexp).each do |c|
            mem <<= c
        end
        i=0
        content.split(regexp).each do |x|
            tmp <<= send(f,x)
            if not mem[i].nil?
                tmp <<= mem[i]
                i+=1
            end
        end
        tmp
    end

An usage is:

    def filter(content)
        content.gsub(/e/,'X')
    end
    ...
    allExceptCode(:filter, content)
    ...

A better syntax would be:

    # !!!!!!!!!! THIS SYNTAX DOES NOT WORK !!!!!!! #
    def allExceptCode( f, content )
        regexp=/<code[^>]*>.*?<\/code>/m
        tmp=""
        content.split(regexp).each do |x|
            separator=$&
            tmp <<= send(f,x)
            if not separator.nil?
                tmp <<= separator
            end
        end
        tmp
    end

I would expect the split make a search on a regular expression and then give the matched expression into the `$&` variable. But it is not the case.

If someone know a nicer way to do that I will be happy to know how.

RSS · Tweet · FB
Ces liens sociaux préservent votre vie privée
↑ Top ↑
Published on 2009-09-22
Follow @yogsototh
Yann Esposito©
Done with Vim spacemacs & nanoc Hakyll

ADA: `DdzFFzCqrhtAvdkmATx5Fm8NPJViDy85ZBw13p4XcNzVzvQg8e3vWLXq23JQWFxPEXK6Kvhaxxe7oJt4VMYHxpA2vtCFiP8fziohN6Yp`