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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |