Search a string with ruby then read what comes after the string in the same line

I am trying to look for a a given string in a text and once i find the
string
I want to be able to store a string that comes after it.

For example I would look for a String "JUNE" and once I find "JUNE" in
the text
I want to store the string that follows JUNE in a variable x. This
string should be 7 characters. So if the text has "JUNE seventh 2012". I
want to be able to store the string seventh in a variable x. Such that
puts x will print seventh on the screen.

This is what I have so far but this only prints the string that I am
looking for. I would like to be able to print the string that comes
after the string I am looking for.

file_names = ['Document.txt']

file_names.each do |file_name|
text = File.read(file_name)

x = text.scan("June")
puts x

end

please advise.

···

--
Posted via http://www.ruby-forum.com/.

You need a regular expression with a capturing group.

Cheers

robert

···

On Tue, Jul 9, 2013 at 7:44 PM, dJD col <lists@ruby-forum.com> wrote:

I am trying to look for a a given string in a text and once i find the
string
I want to be able to store a string that comes after it.

For example I would look for a String "JUNE" and once I find "JUNE" in
the text
I want to store the string that follows JUNE in a variable x. This
string should be 7 characters. So if the text has "JUNE seventh 2012". I
want to be able to store the string seventh in a variable x. Such that
puts x will print seventh on the screen.

This is what I have so far but this only prints the string that I am
looking for. I would like to be able to print the string that comes
after the string I am looking for.

file_names = ['Document.txt']

file_names.each do |file_name|
text = File.read(file_name)

x = text.scan("June")
puts x

end

please advise.

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

Something like this should do it:

s="MAY seventh 2013\nJUNE seventh 2012\nJULY eighth 2014"

=> "MAY seventh 2013\nJUNE seventh 2012\nJULY eighth 2014"

s.scan /June (.{7})/i

=> [["seventh"]]

Of course you might want to capture a whole word rather than exactly
seven characters:
/June (\w+)/i
or
/June (\w{7,})/i

···

--
Posted via http://www.ruby-forum.com/\.

Joel Pearson wrote in post #1114921:

Something like this should do it:

s="MAY seventh 2013\nJUNE seventh 2012\nJULY eighth 2014"

=> "MAY seventh 2013\nJUNE seventh 2012\nJULY eighth 2014"

s.scan /June (.{7})/i

=> [["seventh"]]

Of course you might want to capture a whole word rather than exactly
seven characters:
/June (\w+)/i
or
/June (\w{7,})/i

Thanks!!! works.

···

--
Posted via http://www.ruby-forum.com/\.

Robert Klemme wrote in post #1114918:

···

On Tue, Jul 9, 2013 at 7:44 PM, dJD col <lists@ruby-forum.com> wrote:

puts x

end

please advise.

You need a regular expression with a capturing group.

Cheers

robert

thanks

--
Posted via http://www.ruby-forum.com/\.