Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm in need of a regex and hopefully someone can help me out. I'm looping through a text file that contains lines such as the following:

some_text1 some_text2 some_text3 some_text4
some_text1 some_text2 some_text3 some_text4 FOUND

I need a regex that will return some_text4 whenever it finds the word FOUND. In other words, I need the word that comes before a given word in a line of text.

One more thing that might help. Given the example above, some_text3 will always end with a colon (:).

Any suggestions would be much appreciated.

Replies are listed 'Best First'.
Re: Regex Needed
by Happy-the-monk (Canon) on Mar 25, 2004 at 01:44 UTC

    m/(\w+) (?=FOUND)/g;

    have a look at perldoc perlre   where look-ahead is mentioned. The example there quite matches your problem.

      I think the OP has a different definition of "word" than Perl does -- in particular, a word can contain a colon. My guess is that the OP wants a word to be any non-whitespace.

      m/(\S+)\s+FOUND/; # The word is now in $1

      I don't see the need to use lookahead for this regex.

      -- 
      LP^>

      That would work, but if the goal is to have the entire match ($&) be the desired word, it should be
      m/\w+(?= FOUND)/g
      If capturing into $1 is the goal,
      m/(\w+) FOUND/g
      is all that is needed.