2

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?

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried doing a.gsub(/ (\<br\>)+ /,"") but its printing the same thing.
"e<gr>y<br>t<gh>hello".gsub(/ (\<br\>)+ /,"") returns "e<gr>y<br>t<gh>hello", the original string unchanged (of course, because there are no matches of the pattern in the original string. Underscoring some of the issues with using regexes on HTML, your pattern will only match break tags that are separated from other text by spaces, and won't handle self-closing XML-style <br/> tags.
2

This should account for <br>, <br /> and <br/> just in case.

str = "Hi and <gr>y<br>t<gh>hello<br />bla<br/> some moar"
puts str.gsub(/<br ?\/?>/,'')

Or using a method like your example:

def extract(str)
   str.gsub(/<br ?\/?>/,'')
end
puts extract("Hi and <gr>y<br>t<gh>hello<br />bla<br/> some moar")

Personally I think is better to have the method return a string and then do puts extract() than having the puts inside the method.

Comments

0

Try the following:

a = a.gsub(/<br>/, '')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.