我有一个包含以下文本的文本文件:
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/