----- Original Message ----- From: ""zhihua li"" <[EMAIL PROTECTED]>
Newsgroups: perl.beginners
To: <beginners@perl.org>
Sent: Monday, October 23, 2006 9:05 PM
Subject: count the characters between the matches


hi netters,

I'm curious if there's any smart code to calculate the "distance" between the matches in a text. Suppose I have a text like this: syhk...yes...uhg;ka=...yes...yiealg.....yes.......ghe;a...yes... Apparently it has multiple words of "yes". I'd like to know how many characters there are between the first and the last "yes". The way I now come up with to do this is to use substitution to "mark" the first and the last match, then use a counting loop to calculate the characters......rather straightforward and stupid method.

Anyone has a better idea about that?

Thanks a lot!

This will give the result you want.

#!/usr/bin/perl
use strict;
use warnings;


$_ = 'syhk...yes...uhg;ka=...yes...yiealg.....yes.......ghe;a...yes...';

if (/.*?(yes).*(yes)/) {
print "position at end of first yes is $+[1]\n";
print "position at beginning of last yes is $-[2]\n";
print "number of characters between first and last is ", $-[2] - ($+[1] -1 );
}

**prints

position at end of first yes is 10
position at beginning of last yes is 58
number of characters between first and last is 49


Chris


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to