yermej
12/8/2007 7:59:00 PM
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")