首页 > 解决方案 > 删除某些字符之间的子字符串

问题描述

我想知道是否有办法从字符串中删除两个胡萝卜之间的所有内容:

"<@000000> I thought you said this would happen?"

要得到:

"I thought you said this would happen?"

我认为使用全局替换会起作用。我尝试使用此代码:

somefile = File.open("Test_Teleó.txt", "a+")
  jdoc.fetch("messages").each do |body|
    ts = body["ts"].to_i
    somefile.puts body["text"].gsub(/[<]/, '').gsub(/[>]/, '').chomp
  end

输出是:

@000000 I thought you said this would happen?

它只删除了胡萝卜而不是字符之间。

有什么建议吗?

标签: rubystring

解决方案


只需对您的代码稍作调整:

File.open("Test_Teleó.txt", "a+") do |somefile|
  jdoc.fetch("messages").each do |body|
    ts = body["ts"].to_i
    somefile.puts body["text"].gsub(/<[^>]*>/, '').chomp 
  end
end

我在open这里也使用了块样式,因为它会在块完成时自动关闭文件。这有助于避免忘记和意外打开文件。


推荐阅读