我想知道是否有一种方法可以从另一个字符串中删除字符串?就像这样:
class String
def remove(s)
self[s.length, self.length - s.length]
end
end
a = "foobar"
a.slice! "foo"
=> "foo"
a
=> "bar"
也有一个没有 '!' 的版本。关于其他版本的更多信息可以在文档中查看: http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21
如何使用 str.gsub("subString", "")
?
请查看 Ruby Doc。
sub
而不是gsub
来删除字符串中的子串,因为原作者只想从字符串开头删除子串,而不是整个字符串(请看他的示例代码)。使用正则表达式会更好,例如:str.sub(/^subString/, '')
-- 因为它确保子串只会从字符串开头被删除。 - Alex DsubString
不包含任何正则表达式特殊字符,则会有风险。 - David Moles/^subString/
是一个字面量,因此我们可以非常确定它不包含任何元字符。如果您要将其他字符串替换为正则表达式,则可以使用以下方法:/#{Regexp.escape(str)}/
。 - Alex DRegexp.escape()
的提示。 - David Moleschomp
:"hello".chomp("llo") #=> "he"
chomp
与 reverse
结合使用:"hello".reverse.chomp("he".reverse).reverse #=> "llo"
。该代码的作用是从字符串开头删除以指定子串结尾的部分,并返回剩余的字符串。 - amoebe如果你的子字符串在字符串的开头或结尾,那么Ruby 2.5+版本引入了如下方法:
如果目标字符串只出现一次,您可以使用:
str[target] = ''
或者str.sub(target, '')
如果您有多个目标的出现,请使用:
str.gsub(target, '')
例如:
asdf = 'foo bar'
asdf['bar'] = ''
asdf #=> "foo "
asdf = 'foo bar'
asdf.sub('bar', '') #=> "foo "
asdf = asdf + asdf #=> "foo barfoo bar"
asdf.gsub('bar', '') #=> "foo foo "
如果您需要进行原地替换,请使用 gsub!
和 sub!
的 "!"
版本。
asdf['bar'] = ''
。 - Peter Butkovicslice
方法并不返回被切割的字符串部分,而是返回“刀”。 - Dylan Pierceslice!
实现这个功能非常容易。 my_string.slice!(my_slice)
my_string
- Bennett Talpersdef remove!(*patterns)
patterns.each do |pattern|
gsub! pattern, ""
end
self
end
来源: http://api.rubyonrails.org/classes/String.html#method-i-remove
该方法移除字符串中的匹配项,并返回结果,原始字符串不被更改。它需要一个正则表达式或字符串参数作为匹配模式,可以选择传递可选的第二个参数,指定用于替换匹配项的字符串。# minus_string.rb
class String
def -(str)
partition(str).values_at(0,2).join
end
end
# Add the following code and issue 'ruby minus_string.rb' in the console to test
require 'minitest/autorun'
class MinusString_Test < MiniTest::Test
A,B,C='abra','cadabra','abracadabra'
def test_C_eq_A_plus_B
assert C == A + B
end
def test_C_minus_A_eq_B
assert C - A == B
end
def test_C_minus_B_eq_A
assert C - B == A
end
end
如果您使用的是最新的 Ruby 版本(>= 2.0),这里有一个建议:使用 Refinements 来代替前面例子中的 String 猴子补丁。
做法很简单:
module MinusString
refine String do
def -(str)
partition(str).values_at(0,2).join
end
end
end
在需要使用它的块之前添加using MinusString
。
这是我会做的事情
2.2.1 :015 > class String; def remove!(start_index, end_index) (end_index - start_index + 1).times{ self.slice! start_index }; self end; end;
2.2.1 :016 > "idliketodeleteHEREallthewaytoHEREplease".remove! 14, 32
=> "idliketodeleteplease"
2.2.1 :017 > ":)".remove! 1,1
=> ":"
2.2.1 :018 > "ohnoe!".remove! 2,4
=> "oh!"
多行格式化:
class String
def remove!(start_index, end_index)
(end_index - start_index + 1).times{ self.slice! start_index }
self
end
end
[]
来表示非感叹号版本。 - Matheus Moreira"foobar".tap{|s| s.slice!("foo")}.upcase
- Ernestdelete
会删除你传递进去的所有字符,因此无法使用它来删除特定的单词。例如:'hello world'.delete('hello') #=> ' wrd'
。 - rusty