Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regular expression in ruby

Tags:

regex

ruby

I am trying to strip all the <br>'s in a given string.

 def extract(a)
    a=a.delete("/ (\<br\>)+ /")
    puts a
    end

    extract("e<gr>y<br>t<gh>hello")

is giving egytghhello as output. Why is the <r> of <gr> and <> of gh not getting printed?

like image 487
Ava Avatar asked Jan 17 '26 20:01

Ava


1 Answers

String.delete doesn't take a regular expression as an argument, it takes a set of letters, all of which will be deleted from the string it's called on.

So, your code is saying: delete any of <, >, b, r, (, ), +, space, and /.

You'd use String.gsub if you wanted to use a regex to remove parts of a string (or gsub! to do the replacing in-place).

The usual caveats about the unreliability of using regular expressions to deal with HTML apply: consider using something like Nokogiri, particularly if you have any parsing or manipulation requirements above and beyond this.

like image 195
John Flatness Avatar answered Jan 20 '26 14:01

John Flatness



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!