On 15/09/2011 19:56, Pascua 9804 wrote:
> Thanks to all who tried to help.  Here's the final answer.
>
>
> #!/usr/bin/env ruby
> string="The quick brown fox jumped over the lazy dog"
> def get_subsection(word, sentence)
> sentence.scan(Regexp.new(/(?:\W{0,1}\w+\W){0,3}over(?:\W{1}\w+){0,3}/))
> end
>
> puts get_subsection("quick", string)
> puts get_subsection("lazy", string)
> puts get_subsection("fox", string)
> puts get_subsection("dog", string)
>
>
> The regex in the middle of the syntax is where I struggled, but with a
> little bit of help from the guru I was able to solve the problem.
>
I think that is a maintenance nightmare!

As Jamie Zawinski said - Some people, when confronted with a problem, 
think "I know, I'll use regular expressions." Now they have two problems.

For large source texts it will be horribly slow, and memory hungry, and 
for large search lists it will slow down even more.  Huge, slow and hard 
to maintain = not good.

What the OP wanted was a sequence of 7 words, where the 4th is the word 
sought, and the string can be missing words "before" or "after" the 
source string.

So you need two parallel lists of strings.  The first is a list of 
tokens from the source, where each token is separated from the next by 
white-space. The second are words, created from the tokens by removing 
punctuation.

Slide through the source, token at a time, and if the forth word of the 
word list is one of the ones you want,
use the token list to reconstruct the fragment of the source, (without 
newlines) and emit the result.

In order to handle the start-up and close-down properly, I would 
consider preloading the token list with null strings, and arrange the 
"get next token" function to return three null strings after end of 
file, before signalling the end.
However there are other methods.

This is one pass, so you don't need the source all in memory. It will be 
order source size in time, and order the number of words sought in 
space.  Fast, compact and easy to alter the rule or length of the lists.

Regards

Ian