【问题标题】:Ruby Regex to keep single apostrophe but remove end apostrophesRuby Regex 保留单个撇号但删除结束撇号
【发布时间】:2016-09-27 01:27:02
【问题描述】:

对于下面的字符串,如何去掉封闭的单引号?

string: "'won't'"
desired result: "won't" 

寻找我可以在gsub 中使用的正则表达式,将'' 替换为空字符串。例如

arr = ["'don't'", "stop", "str%&eaming"]
arr.map { |letter| gsub(/pattern/, ""}

应该返回

=> ["don't", "stop", "streaming"]

【问题讨论】:

  • 你能有一个字符串,"'don't' or "'won't'" 还是总是只有一个带有三个单引号/撇号的单词?如果该字符出现在两个字母之间,是否一定是撇号(保留)?

标签: arrays ruby regex string


【解决方案1】:

这在 irb 中对我有用

arr.map { |l| l.gsub(/^'|'$|%&/, '') }

注意,这不会修改原来的方式。要破坏性地改变数组,您需要使用bang 方法,在本例中为arr.map!

这里是一个简单的解释。

在正则表达式中,我们正在搜索以撇号开头或结尾的匹配项,或者在第三项中包含两个特殊字符的匹配项。

符号^ 用于表示该行以某个子字符串开头。另一方面,符号$ 用于表示以某个子字符串结尾的行。 | 运算符在计算机科学中很常见,用于表示 or 条件。

但是,如果您有一个跨越多行的字符串,您应该考虑使用\A\z 表达式来指示字符串的开始和结束。

我在irb中的输出如下

=> ["don't", "stop", "streaming"]

【讨论】:

  • 我喜欢解决方案的扩展性,即如果他们想将 "don't' stop" (although not part of the OP yet) this could be modified from ^'|'$` 等单词之间的单引号替换为 ^'|'$|'\s
  • ^ 表示 line 的开头,而不是 Ruby 中的 string;另一端的$ 也是如此。在 Ruby 中,您几乎总是需要 \A\z
  • 一个问题:"'twas".gsub(/^'|'$|%&/, '') #=> "twas".
  • %& 是非单词字符的示例。如果我想过滤所有非单词字符,我将如何编辑正则表达式...arr.map { |l| l.gsub(/^'|'$|\W/, '') } - 这不起作用arr.map { |l| l.gsub(/^'|'$|[\.!&*:,@$%^], '') } - 这确实
【解决方案2】:

保持简单。

def strip_single_quotes(str)
  str[0]=="'" && str[-1]=="'" ? str[1..-2] : str
end

arr = ["'don't'", "stop", "str%&eaming", "'twas", "''twas'", "'fishin''", "she'd've"]

arr.each { |word| puts "#{word.ljust(12)} -> #{strip_single_quotes(word) }" }
'don't'      -> don't
stop         -> stop
str%&eaming  -> str%&eaming
'twas        -> 'twas
''twas'      -> 'twas
'fishin''    -> fishin'
she'd've     -> she'd've

您可以改写strip_single_quotes 的正文,如下所示。

str =~ /\A'.*'\z/ ? str[1..-2] : str

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 2018-05-13
    • 2013-05-07
    • 1970-01-01
    相关资源
    最近更新 更多