如何使用`gsub`用相同的字符串替换多个子字符串 [英] How to replace multiple substrings with same string using `gsub`

查看:246
本文介绍了如何使用`gsub`用相同的字符串替换多个子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将不同的字符/子字符串更改为单个字符或nil.我想将"How to chop an onion?"更改为"how-chop-onion".

I want to change different charaters/substrings to a single character or nil. I want to change "How to chop an onion?" to "how-chop-onion".

string
.gsub(/'s/,'')
.gsub(/[?&]/,'')
.gsub('to|an|a|the','')
.split(' ')
.map { |s| s.downcase}
.join '-'

使用管道字符|不起作用.如何使用gsub做到这一点?

Using pipe character | does not work. How can I do this with gsub?

推荐答案

to|an|a|the是模式,您将其用作String.在这里:

to|an|a|the is pattern, you are using it as String. Here:

str.gsub('to|an|a|the', '')   # passing string argument
#=> "How to chop an onion?"

str.gsub(/to|an|a|the/, '')   # passing pattern argument
#=> "How  chop  onion?"

这篇关于如何使用`gsub`用相同的字符串替换多个子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆