简体   繁体   中英

Removing a pattern from the beginning and end of a string in ruby

So I found myself needing to remove <br /> tags from the beginning and end of strings in a project I'm working on. I made a quick little method that does what I need it to do but I'm not convinced it's the best way to go about doing this sort of thing. I suspect there's probably a handy regular expression I can use to do it in only a couple of lines. Here's what I got:

def remove_breaks(text)  
    if text != nil and text != ""
        text.strip!

        index = text.rindex("<br />")

        while index != nil and index == text.length - 6
            text = text[0, text.length - 6]

            text.strip!

            index = text.rindex("<br />")
        end

        text.strip!

        index = text.index("<br />")

        while index != nil and index == 0
            text = test[6, text.length]

            text.strip!

            index = text.index("<br />")
        end
    end

    return text
end

Now the "<br />" could really be anything, and it'd probably be more useful to make a general use function that takes as an argument the string that needs to be stripped from the beginning and end.

I'm open to any suggestions on how to make this cleaner because this just seems like it can be improved.

gsub can take a regular expression:

text.gsub!(/(<br \/>\s*)*$/, '')
text.gsub!(/^(\s*<br \/>)*/, '')
text.strip!
class String
    def strip_this!(t)
        # Removes leading and trailing occurrences of t
        # from the string, plus surrounding whitespace.
        t = Regexp.escape(t)
        sub!(/^(\s* #{t} \s*)+  /x, '')
        sub!(/ (\s* #{t} \s*)+ $/x, '')
    end
end

# For example.
str = ' <br /> <br /><br />    foo bar <br />    <br />   '
str.strip_this!('<br />')
p str                     # => 'foo bar'

You can use chomp! and slice! methods. See: http://ruby-doc.org/core-1.8.7/String.html

def remove_breaks(text)
  text.gsub((%r{^\s*<br />|<br />\s*$}, '')
end

%r{...} is another way to specify a regular expression. The advantage of %r is that you can pick your own delimeter. Using {} for the delimiters means not having to escape the /'s.

请改用替换方法

str.replace("<br/>", "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM