在Ruby中,如何替换字符串中的问号字符?

时间:2023-02-04 22:24:06

In Ruby, I have:

在Ruby中,我有:

require 'uri'
foo = "et tu, brutus?"
bar = URI.encode(foo)      # => "et%20tu,%20brutus?"

I'm trying to get bar to equal "et%20tu,%20brutus%3f" ("?" replaced with "%3F") When I try to add this:

我试图让bar等于“et%20tu,%20brutus%3f”(“?”替换为“%3F”)当我尝试添加这个时:

bar["?"] = "%3f"

the "?" matches everything, and I get

“?”匹配一切,我明白了

=> "%3f"

I've tried

bar["\?"]
bar['?']
bar["/[?]"]
bar["/[\?]"]

And a few other things, none of which work.

还有一些其他的东西,都没有用。

Hints?

Thanks!

4 个解决方案

#1


12  

require 'cgi' and call CGI.escape

要求'cgi'并调用CGI.escape

#2


4  

Here's a sample irb session :

这是一个示例irb会话:

irb(main):001:0> x = "geo?"

irb(主要):001:0> x =“geo?”

=> "geo?"

irb(main):002:0> x.sub!("?","a")

=> "geoa"

irb(main):003:0>

However, sub will only replace the first character . If you want to replace all the question marks in a string , use the gsub method like this :

但是,sub只会替换第一个字符。如果要替换字符串中的所有问号,请使用gsub方法,如下所示:

str.gsub!("?","replacement")

#3


3  

There is only one good way to do this right now in Ruby:

现在只有一种方法可以在Ruby中执行此操作:

require "addressable/uri"
Addressable::URI.encode_component(
  "et tu, brutus?",
  Addressable::URI::CharacterClasses::PATH
)
# => "et%20tu,%20brutus%3F"

But if you're doing stuff with URIs you should really be using Addressable anyways.

但是,如果你正在使用URI,你应该真正使用Addressable。

sudo gem install addressable

#4


0  

If you know which characters you accept, you can remove those that don't match.

如果您知道接受哪些字符,则可以删除那些不匹配的字符。

accepted_chars = 'A-z0-9\s,'
foo = "et tu, brutus?"
bar = foo.gsub(/[^#{accepted_chars}]/, '')

#1


12  

require 'cgi' and call CGI.escape

要求'cgi'并调用CGI.escape

#2


4  

Here's a sample irb session :

这是一个示例irb会话:

irb(main):001:0> x = "geo?"

irb(主要):001:0> x =“geo?”

=> "geo?"

irb(main):002:0> x.sub!("?","a")

=> "geoa"

irb(main):003:0>

However, sub will only replace the first character . If you want to replace all the question marks in a string , use the gsub method like this :

但是,sub只会替换第一个字符。如果要替换字符串中的所有问号,请使用gsub方法,如下所示:

str.gsub!("?","replacement")

#3


3  

There is only one good way to do this right now in Ruby:

现在只有一种方法可以在Ruby中执行此操作:

require "addressable/uri"
Addressable::URI.encode_component(
  "et tu, brutus?",
  Addressable::URI::CharacterClasses::PATH
)
# => "et%20tu,%20brutus%3F"

But if you're doing stuff with URIs you should really be using Addressable anyways.

但是,如果你正在使用URI,你应该真正使用Addressable。

sudo gem install addressable

#4


0  

If you know which characters you accept, you can remove those that don't match.

如果您知道接受哪些字符,则可以删除那些不匹配的字符。

accepted_chars = 'A-z0-9\s,'
foo = "et tu, brutus?"
bar = foo.gsub(/[^#{accepted_chars}]/, '')