ruby - 如何在ruby中获取两个字符串之间的文本?

标签 ruby regex string parsing

我有一个包含以下文本的文本文件:

What's New in this Version
==========================
-This is the text I want to get 
-It can have 1 or many lines
-These equal signs are repeated throughout the file to separate sections

Primary Category
================

我只想获取 ========================== 和 Primary Category 之间的所有内容,并将该文本 block 存储在一个变量中。我认为以下匹配方法会起作用,但它给了我 NoMethodError: undefined method `match'

    f = File.open(metadataPath, "r")
    line = f.readlines
    whatsNew = f.match(/==========================(.*)Primary Category/m).strip

有什么想法吗?提前致谢。

最佳答案

f 是一个文件描述符 - 您想要匹配文件中的文本,您将其读入 line。我更愿意做的不是将文本读入一个数组(很难用正则表达式),而是将它读入一个字符串:

contents = File.open(metadataPath) { |f| f.read }
contents.match(/==========================(.*)Primary Category/m)[1].strip

最后一行产生你想要的输出:

-This is the text I want to get \n-It can have 1 or many lines\n-These equal signs are repeated throughout the file to separate sections"

关于ruby - 如何在ruby中获取两个字符串之间的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6991673/

相关文章:

ruby-on-rails - rails 奇怪的单元测试失败

ruby - 为什么会出现段错误 (qtruby)?

regex - 非常大的文件之间的 Grep 模式匹配太慢了

mysql - 无法找到一种方法来否定模式内的正则表达式

java - java中的字符串操作

javascript - 将字符串拆分为字符之间的数组?

ruby - 无法识别 Jekyll 插件

ruby - 克隆一个数组及其内容

python - Python中根据某些单词分割字符串并删除某些特殊字符

string - 删除动态字符串中的最后一个字符