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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Count matches...with exclusions 1

Status
Not open for further replies.

CJason

Programmer
Oct 13, 2004
223
US
I'm trying to count the number of "A" characters in a string that are not preceeded AND followed by a "C". So:
Code:
$string = "ABCACAB";
should come back with a count of 2 "A" characters. Any ideas/suggestions? I tried:
Code:
$count = 0;
$count++ while ($string =~ m/(?<!C)A(?!C)/g);
but count returns with 1, not 2. I guess because it's trying to find matches where A is not preceeded OR followed by a "C"????
 
this might need testing to see if it works with more than just your test string:

Code:
$count while ($string =~ m/[AB]?(?!<C)A(?!C)[AB]?/g);

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
should be:

Code:
$count[red]++[/red] while ($string =~ m/[AB]?(?!<C)A(?!C)[AB]?/g);

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
You'll probably want to test this a little better, but it appears to be working:
Code:
foreach (qw/ABCACAB ABCAACAB AABCACCAACACABA/) {
	print "$_: " . (() = ([blue][b]m/(?(?<!C)A|A(?!C))/g[/b][/blue])) . "\n";
}
 
Kevin

Code:
$count++ while ($string =~ m/[AB]?(?!<C)A(?!C)[AB]?/g);

A while loop on a regexp goes through and stops at the end if the "g" tag is on there?

A few times I've wanted to do something like this, but got into infinite loops all the time, and the only solution I could see was to substitute the regexp out of the string one time for each loop, but then sometimes (especially if the regexp is complicated) I make a typo and it still causes an infinite loop.

Cuvou.com | My personal homepage
Code:
perl -e '$|=$i=1;print" oo\n<|>\n_|_";x:sleep$|;print"\b",$i++%2?"/":"_";goto x;'
 
A while loop on a regexp goes through and stops at the end if the "g" tag is on there?

Yes. Its discussed in perlrequick:


If you forget the 'g' modifier, a "while" loop could very well never end.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top