ruby 如何从Ruby中的字符串中删除特定字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19637677/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:15:55  来源:igfitidea点击:

How to delete specific characters from a string in Ruby?

rubystringtrim

提问by Cristiano

I have several strings that look like this:

我有几个看起来像这样的字符串:

"((String1))"

They are all different lengths. How could I remove the parentheses from all these strings in a loop?

它们都是不同的长度。如何从循环中的所有这些字符串中删除括号?

回答by Arup Rakshit

Do as below using String#tr:

使用以下方法执行以下操作String#tr

 "((String1))".tr('()', '')
 # => "String1"

回答by jbr

If you just want to remove the first two characters and the last two, then you can use negative indexeson the string:

如果您只想删除前两个字符和后两个字符,则可以在字符串上使用负索引

s = "((String1))"
s = s[2...-2]
p s # => "String1"

If you want to remove all parentheses from the string you can use the deletemethod on the string class:

如果要从字符串中删除所有括号,可以在字符串类上使用delete方法:

s = "((String1))"
s.delete! '()'
p s #  => "String1"

回答by falsetru

Using String#gsubwith regular expression:

String#gsub与正则表达式一起使用:

"((String1))".gsub(/^\(+|\)+$/, '')
# => "String1"
"(((((( parentheses )))".gsub(/^\(+|\)+$/, '')
# => " parentheses "

This will remove surrounding parentheses only.

这将仅删除周围的括号。

"(((((( This (is) string )))".gsub(/^\(+|\)+$/, '')
# => " This (is) string "

回答by daino3

For those coming across this and looking for performance, it looks like #deleteand #trare about the same in speed and 2-4x faster than gsub.

对于那些遇到此问题并寻求性能的人来说,它的速度看起来#delete#tr几乎相同,并且比gsub.

text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04

回答by zee

Here is an even shorter way of achieving this:

这是实现这一目标的更短的方法:

1) using Negative character class pattern matching

1) 使用 Negative character class pattern matching

irb(main)> "((String1))"[/[^()]+/]
=> "String1"

^- Matches anything NOT in the character class. Inside the charachter class, we have (and )

^- 匹配任何不在字符类中的东西。在字符类中,我们有()

Or with global substitution "AKA: gsub" like others have mentioned.

或者像其他人提到的那样使用全局替换“AKA:gsub”。

irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"