#!/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 () { # first method my $valid_data = substr($_, $start_boundary, $end_boundary - $start_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