Ruby gsub 的正则表达式
Regex with Ruby gsub
我的目标是用输入中的 '-'
替换 spaces 和 "/"
:
name = "chard / pinot noir"
得到:
"chard-pinot-noir"
我的第一次尝试是:
name.gsub(/ \/\ /, '-') #=> "chart-pinot noir"
我的第二次尝试是:
name.gsub(/\/\s+/, '-') #=> "chard -pinot noir"
我的第三次尝试是:
name.gsub(/\s+/, '-') #=> "chard-/-pinot-noir"
有帮助。第一组检查正斜杠 /
,并包含一个分隔符。第二部分将正斜杠替换为 '-'
。但是,space 仍然存在。我相信 /s
匹配 spaces,但我无法在同时检查正斜杠的同时让它工作。
我的问题是,如何使用正则表达式或 ruby 帮助程序使用不同的字符串获得所需的结果,如上所示。有首选方法吗?赞成/反对?
如果你对regex不是很了解,你可以这样做。
name = "chard / pinot noir"
(name.split() - ["/"]).join("-")
=> "chard-pinot-noir"
我认为最好的方法是与 regex 一起使用,如上文所述 @Sagar Pandya。
name.gsub(/[\/\s]+/,'-')
=> "chard-pinot-noir"
我的目标是用输入中的 '-'
替换 spaces 和 "/"
:
name = "chard / pinot noir"
得到:
"chard-pinot-noir"
我的第一次尝试是:
name.gsub(/ \/\ /, '-') #=> "chart-pinot noir"
我的第二次尝试是:
name.gsub(/\/\s+/, '-') #=> "chard -pinot noir"
我的第三次尝试是:
name.gsub(/\s+/, '-') #=> "chard-/-pinot-noir"
/
,并包含一个分隔符。第二部分将正斜杠替换为 '-'
。但是,space 仍然存在。我相信 /s
匹配 spaces,但我无法在同时检查正斜杠的同时让它工作。
我的问题是,如何使用正则表达式或 ruby 帮助程序使用不同的字符串获得所需的结果,如上所示。有首选方法吗?赞成/反对?
如果你对regex不是很了解,你可以这样做。
name = "chard / pinot noir"
(name.split() - ["/"]).join("-")
=> "chard-pinot-noir"
我认为最好的方法是与 regex 一起使用,如上文所述 @Sagar Pandya。
name.gsub(/[\/\s]+/,'-')
=> "chard-pinot-noir"