Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text between two strings in ruby?

I have a text file that contains this text:

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
================

I just want to get everything between ========================== and Primary Category and store that block of text in a variable. I thought the following match method would work but it gives me, NoMethodError: undefined method `match'

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

Any ideas? Thanks in advance.

like image 921
Abdulla Avatar asked Mar 05 '26 17:03

Abdulla


1 Answers

f is a file descriptor - you want to match on the text in the file, which you read into line. What I prefer to do instead of reading the text into an array (which is hard to regex on) is to just read it into one string:

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

The last line produces your desired output:

-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"
like image 114
Chris Bunch Avatar answered Mar 07 '26 07:03

Chris Bunch