----- # Custom isHidden: false menupriority: 1 kind: article created_at: 2009-09-22T22:13:25+02:00 title: replace all except some part multiTitle: fr: replace all except some part en: replace all except some part multiDescription: fr: pas de description. en: no description. tags: - ruby - regexp - regular expression ----- 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
...
def allExceptCode( f, content )
regexp=/]*>.*?<\/code>/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
def filter(content)
content.gsub(/e/,'X')
end
...
allExceptCode(:filter, content)
...
# !!!!!!!!!! THIS SYNTAX DOES NOT WORK !!!!!!! #
def allExceptCode( f, content )
regexp=/]*>.*?<\/code>/m
tmp=""
content.split(regexp).each do |x|
separator=$&
tmp <<= send(f,x)
if not separator.nil?
tmp <<= separator
end
end
tmp
end