Using regular expression in 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 p开发者_JS百科rinted?
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.
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.
Try the following:
a = a.gsub(/<br>/, '')
精彩评论