非空格字符的剥离方法?

5
5个回答

3

我不知道是否在这里重新发明轮子,如果您找到一个内置方法可以做相同的事情,请告诉我 :-)

我添加了以下内容到config/initializers/string.rb,它向String类添加了trimltrimrtrim方法。

# in config/initializers/string.rb
class String
  def trim(str=nil)
    return self.ltrim(str).rtrim(str)
  end

  def ltrim(str=nil)
    if (!str)
      return self.lstrip
    else
      escape = Regexp.escape(str)
    end

    return self.gsub(/^#{escape}+/, "")
  end

  def rtrim(str=nil)
    if (!str)
      return self.rstrip
    else
      escape = Regexp.escape(str)
    end

    return self.gsub(/#{escape}+$/, "")
  end
end

我这样使用它:

"... hello ...".trim(".") => " hello "

还有这个:

"\"hello\"".trim("\"") => "hello"

希望这对你有所帮助 :-)


2
您可以使用tr函数,并将第二个参数设置为空字符串。例如:

tr函数用于替换字符串中的字符,可以实现一些简单的文本处理功能。

%("... text... ").tr('"', '')

会移除所有双引号。

如果你使用这个函数来清理输入或输出,那么它可能无法有效地防止SQL注入或跨站脚本攻击。对于HTML,最好使用gem sanitize或视图助手函数h


3
但我只想替换字符串/文本开头和结尾的引号。 - alamodey

1

我不知道有没有现成的,但这个应该可以满足你的需求:

class String
  def strip_str(str)
    gsub(/^#{str}|#{str}$/, '')
  end
end

a = '"Hey, there are some extraneous quotes in this here "String"."'
puts a.strip_str('"') # -> Hey, there are some extraneous quotes in this here "String".

1
请注意,^$匹配行的开头和结尾。您需要使用\A\z来匹配字符串的开头和结尾。 - David Phillips

0
你可以使用String#gsub:
%("... text... ").gsub(/\A"+|"+\Z/,'')

实际上应该是小写的\z - David Phillips

0
class String
    # Treats str as array of char
  def stripc(str)
    out = self.dup
    while str.each_byte.any?{|c| c == out[0]}
        out.slice! 0
    end
    while str.each_byte.any?{|c| c == out[-1]}
        out.slice! -1
    end
    out
  end
end

如果你想要删除所有额外的字符串模式实例,那么Chuck的答案需要一些+符号。而且,如果你想要删除任意顺序出现的一组字符中的任何一个,它是不起作用的。

例如,如果我们希望一个字符串不以以下任何一个结尾:a, b, c,并且我们的字符串是fooabacab,我们需要像我上面提供的代码一样更强大的东西。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接