忽略文本的标题内容

时间:2011-03-28 18:04:14

标签: ruby

我想在“这个词”之前删除文件的内容 并且只将该字后面的行写到磁盘上。

text = <<EOT
  I only want
  the last lines
  of the file after
  this word. This is
  the content I 
  want. Yet this
  word can appear again.
EOT

puts text.scan("this word")

预期产出:

This is
the content I 
want. Yet this
word can appear again.

最有效的方法是什么?

任何帮助表示赞赏

泰德。

4 个答案:

答案 0 :(得分:1)

如果“此单词”在测试中只出现一次,或者您想删除最后一个短语:

text.sub(/.*this word\W*/, '')

如果'this word'有可能出现多次,并且您只想删除第一个这样的话:

text.sub(/.*?this word\W*/, '')

答案 1 :(得分:0)

喜欢这个吗?

irb(main):001:0> text = <<EOT
irb(main):002:0"   I only want
irb(main):003:0"   the last lines
irb(main):004:0"   of the file after
irb(main):005:0"   this word. This is
irb(main):006:0"   the content I 
irb(main):007:0"   want.
irb(main):008:0" EOT
=> "  I only want\n  the last lines\n  of the file after\n  this word. This is\n  the content I \n  want.\n"
irb(main):009:0> needle = 'this word. '
=> "this word. "
irb(main):012:0> text[text.index(needle)+needle.length..-1]
=> "This is\n  the content I \n  want.\n"
irb(main):013:0> print text[text.index(needle)+needle.length..-1]
This is
  the content I 
  want.
=> nil

答案 2 :(得分:0)

一种简单的方法是使用分区方法:

text.partition("this word. ").last

(这假定“这个词。”实际上出现在变量文本中。如果没有,则此代码将返回一个空字符串。)

答案 3 :(得分:0)

一种方式:

text.split('this word. ')[1]

或者

text.split('this word. ').last