【问题标题】:Regex with Ruby gsub [duplicate]使用 Ruby gsub 的正则表达式 [重复]
【发布时间】:2018-04-23 20:36:18
【问题描述】:

我的目标是用输入中的'-' 替换空格和"/"

name = "chard / pinot noir"

得到:

"chard-pinot-noir"

我的第一次尝试是:

name.gsub(/ \/\ /, '-') #=> "chart-pinot noir"

我的第二次尝试是:

name.gsub(/\/\s+/, '-') #=> "chard -pinot noir"

我的第三次尝试是:

name.gsub(/\s+/, '-') #=> "chard-/-pinot-noir"

This article 提供帮助。第一组检查正斜杠/,并包含一个中断。第二部分用'-' 替换正斜杠。但是,空间仍然存在。我相信/s 匹配空格,但我无法让它在同时检查正斜杠的同时工作。

我的问题是如何使用正则表达式或 ruby​​ 助手获得所需的结果,如上所示,使用不同的字符串。有首选方法吗?赞成/反对?

【问题讨论】:

  • name.gsub(/[\/\s]+/,'-') #=> "chard-pinot-noir"
  • @SagarPandya 谢谢!正则表达式上的文档令人困惑。 +/ 正则表达式是用于检查所有正斜杠吗?作为答案,我可以报告为已回答。
  • [\/\s]+ 检查/ 或空白字符中的一个或多个。 Rublar 有一个不错的备忘单,如果你想玩的话。
  • 你的问题是什么?

标签: ruby regex replace gsub


【解决方案1】:

如果你对regex不太了解,可以这样做。

name = "chard / pinot noir"
(name.split() - ["/"]).join("-")
=> "chard-pinot-noir"

我认为最好的方法是使用regex 和上面描述的@Sagar Pandya

name.gsub(/[\/\s]+/,'-')
=> "chard-pinot-noir"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多