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

Dear monks

I'm trying to find the position of the match BEGINNING found with the following Regex, but I have really no idea how. The problem is that I'm searching in a span, so I really do not know how to come to the beginning position (I normally find it counting the length (characters) of the matching variables and "moving back" of that value starting from the pos($text) value).

my $text=<<EOF I'm trying to find the position of the match BEGINNING found with the +following Regex, but I have really no idea how. The problem is that I +'m searching in a span, so I really do not know how to come to the be +ginning position (I normally find it counting the length (characters) + of the matching variables and "moving back" of that value starting f +rom the pos($text) value). EOF my $UserInputPart1 = "to"; my $UserInputPart1 = "the"; while (($text=~ /$UserInputPart1\W+(?:\w+\W+){0,5}?$UserInputPart2/gi) + || ($text=~ /$UserInputPart2\W+(?:\w+\W+){0,5}?$UserInputPart1/gi)){ my $position = pos($text); print $position . "\n"; }

Replies are listed 'Best First'.
Re: Find initial position of match iin regexp with variable span
by AppleFritter (Vicar) on Oct 14, 2015 at 09:36 UTC

    Hi, and welcome to the monastery! First of all, please, post code that compiles. Yours does not:

    syntax error at 1144824.pl line 4, near "my "
      (Might be a runaway multi-line << string starting on line 2)
    Execution of 1144824.pl aborted due to compilation errors.
    

    That said, could you explain more clearly what it is you're trying to achieve? For starters, what's the desired output of your code?

      Sorr for the code that doesnn't compile, I just build it on the run around the Regexp. Anyway, I found the solution. If:

      my $position = pos($text);

      finds the matching position at the END of the pattern

      my $position = ($-[0]);

      finds the matching position at the BEGINNING of the pattern.