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

W

wx

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.
 
Y

yermej

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")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top