[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Regexp: str1-anything but str2-str2 => str1-str2

wx

12/8/2007 4:22:00 PM

A simple question about whether this can be done with regular
expressions in Ruby:

str = <<EOS
start
<script>
function test(a) {
return a < 5;
}
</script>
between1
<script>
function test2(a) {
return a == 15;
}
</script>
between2
<script>
function test2(a) {
return a / 15;
}
</script>
between3
<script>
function test(a) {
return (a / 15) < 5;
}
</script>
between4
<script>
function test(a) {
return 5 < (a / 15);
}
</script>
end
EOS
re = /what here?!/
puts str.gsub(re, '----------------- zapped -------------------')

Can re be written so the output is similar to:

start
between1
between2
between3
between4
end

I tried the following, but no luck:
re = /<script>(<\/script>){0}.*<\/script>/m
re = /<script>[^<]*[^\/]*<\/script>/m
re = /<script>([^<][^\/])*<\/script>/m
re = /<script>([^<]|[^\/])*<\/script>/m

Any other simple way? The next thing I will do is find <script>, find
the next </script> and replace anything in between, but regexps are
just sweet, so I was still trying with them.
2 Answers

yermej

12/8/2007 7:59:00 PM

0

On Dec 8, 10:21 am, wx <wi...@yahoo.com> wrote:
> A simple question about whether this can be done with regular
> expressions in Ruby:
>
> str = <<EOS
> start
> <script>
> function test(a) {
> return a < 5;}
>
> </script>
> between1
> <script>
> function test2(a) {
> return a == 15;}
>
> </script>
> between2
> <script>
> function test2(a) {
> return a / 15;}
>
> </script>
> between3
> <script>
> function test(a) {
> return (a / 15) < 5;}
>
> </script>
> between4
> <script>
> function test(a) {
> return 5 < (a / 15);}
>
> </script>
> end
> EOS
> re = /what here?!/
> puts str.gsub(re, '----------------- zapped -------------------')
>
> Can re be written so the output is similar to:
>
> start
> between1
> between2
> between3
> between4
> end
>
> I tried the following, but no luck:
> re = /<script>(<\/script>){0}.*<\/script>/m
> re = /<script>[^<]*[^\/]*<\/script>/m
> re = /<script>([^<][^\/])*<\/script>/m
> re = /<script>([^<]|[^\/])*<\/script>/m
>
> Any other simple way? The next thing I will do is find <script>, find
> the next </script> and replace anything in between, but regexps are
> just sweet, so I was still trying with them.

A non-greedy regex (.*? in this case) makes this pretty easy:

str.gsub(/<script>.*?<\/script>/m, '').gsub(/\n+/, "\n")

wx

12/8/2007 8:05:00 PM

0

yermej,

Thanks, that worked wonderfully!