在 ruby 字符串中正确使用 gsub
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18193424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using gsub in ruby strings correctly
提问by banditKing
I have this expression:
我有这样的表达:
channelName = rhash["Channel"].gsub("'", " ")
it works fine. However, I can only substitute 1 character with it. I want to add a few more characters to substitue. So I tried the following:
它工作正常。但是,我只能用它替换 1 个字符。我想再添加几个字符来替代。所以我尝试了以下方法:
channelName = rhash["Channel"].gsub(/[':;] /, " ")
This did not work, that is there was no substitution done on strings and no error message. I also tried this:
这不起作用,即没有对字符串进行替换,也没有错误消息。我也试过这个:
channelName = rhash["Channel"].gsub!("'", " ")
This lead to a string that was blank. So absolutely not what I desired.
这导致字符串为空。所以绝对不是我想要的。
I would like to have a gsub method to substitute the following characters with a space in my string:
我想要一个 gsub 方法来用我的字符串中的空格替换以下字符:
' ; :
My questions:
我的问题:
How can I structure my gsub method so that all instances of the above characters are replaced with a space?
What is happening with gsub! above as its returning a blank.
如何构建我的 gsub 方法,以便将上述字符的所有实例替换为空格?
gsub 发生了什么!上面作为它返回一个空白。
回答by Dylan Markow
Your second attempt was very close. The problem is that you left a space after the closing bracket, meaning it was only looking for one of those symbols followed by a space.
你的第二次尝试非常接近。问题是您在右括号后留下了一个空格,这意味着它只是在寻找其中一个后跟一个空格的符号。
Try this:
尝试这个:
channelName = rhash["Channel"].gsub(/[':;]/, " ")
回答by sawa
This does not answer your question, but is a better way to do it.
这并不能回答您的问题,而是一种更好的方法。
channelName = rhash["Channel"].tr("':;", " ")

