Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using REGEX - question. 2

Status
Not open for further replies.

garymgordon

Programmer
Apr 5, 2000
307
0
0
US
I have the following that I am using in order to find as many matches as possible and then print out the number of matches found, and which letters were found in the match.

Here is what I have:

$letters5 = "AARON FOOBARR SMITTH";
if( $letters5 =~ m/\w*(.)\1\w*/g ){
print "\n";
print "matched $&\n";
print "1 = $1\n";
print "\n\n";
}

But, I get the same result with or without the /g at the end. I am trying to figure out how to have the match (maybe re-written) so it will not only match the first set of double letters - but as many as it can find. Then, print out for me the total number of matches found, and which words contained the matches ... and which letters were matched.

Help ... please?

Thanks,
Gary

PS: What am I doing wrong here?



 
Just use 'while' rather than 'if'.

while ($letters5 =~ /\w*(.)\1\w*/g)
{
# print stuff
}


keep the rudder amid ship and beware the odd typo
 
if you just want the number times it matches, evaluate the regular expression with 'g' on, assign that to an array, then evaluate that array in scalar context:[tt][color]
@matches = m/PATTERN/g;
$count = scalar(@matches);
[/tt][/color]
however, this has only two situations that it will work. one is if there are no parantheses enclosed substrings in the regex, in which case the elements of the array will be the $& values of each match. the other is if there is only one set of parentheses, in which case the array will be the values of $1 for each match, and $& will be unavailable. if there is more than one set of parentheses, the array will be ($1, $2, $3, $1, $2, $3, ...), with one entry for each parens in every match. you could then break this apart, so you could effectively have your $& by:[tt]
m~(A (SUB)PATTERN)~g[/tt]

in which case $1 would be the equivelent of $&, and $2 would be the little snippit, but this would make the array it returns less ledgible and harder to deal with. if you need access to $& and $1, your loop works well. you can set an iterator ($i++;) in the loop to count the number of matches. "If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito."
 
Stillflame,

Thanks. Your answer is a little over 'my' head at this point, but I will look it over and try to understand it. Thanks for the additional feedback!! :)) Always appreciated.

Gary
Gary M. Gordon, LLC
webmaster@garymgordon.com
Certified Web Developer ::
Application Programmer
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top