Greetings Monks.

I am parsing a large chunk of text, extracting the lines where a regex matches a given portion of each row. It means that the regex should only match if the pattern is found within a predefined portion of the row.

For example, I have this (simplified) code:

#!/usr/bin/perl use strict; use warnings; # text should only match within these positions my ($start_boundary, $end_boundary) = (11, 30); my $regex = qr/hello world/i; while (<DATA>) { # first method my $valid_data = substr($_, $start_boundary, $end_boundary - $star +t_boundary +1); if ( $valid_data =~ $regex ) { printf "1) %d %d '%s'\n", $-[0], $+[0], substr($_, $-[0] + $start_boundary , $+[0] - $-[0]) +; } # second method if ( m/$regex/ ) { if ( $-[0] > $start_boundary && $+[0] < $end_boundary ) { printf "2) %d %d '%s'\n", $-[0], $+[0], substr($_, $-[0], $+[0] - $-[0]); } } } __DATA__ some meaningful text containing "hello world" and more hello world should not match here in this row Hello World could match also here my HELLO world has a chance here hello world should be skipped

I want to match the regex (in the real case, it is much more complex than this) only between positions 11 and 30 in the source string.

Both methods that I have found work, i.e. they find the right text. However, the first method needs too much calculation, while the second method will apply the regex to all the lines, and only a subsequent filter will find out if it was a right match.

So, the questions are:

TIA

update Code in first method fixed. Thanks to Roger.

Code in second method is wrong, as ikegami and japhy noted.


In reply to Applying a regex to part of a string by holdyourhorses

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.