[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] counting in REs



>    3)  test for an even number of 'a's
>        and      an odd  number of 'b's in a string

I offer this solution:

  # regex to match even # of a's and odd # of b's
  $str = "a bat and a ball are bad for football, but good for baseball.";
  print "even a's, odd b's" if $str =~ /
    (?=			# just look ahead for
      ^			# beginning of string
      (
        ([^a]*a){2}	# any non-a, then a, look for it twice
      )*		# look for couplet any # of times (INCLUDING 0)
      [^a]*		# look for non-a
      $			# and then end of string
    )
    (?=			# also look ahead for
      ^			# beginning of string
      [^b]*b		# any non-b, then b
      (
        ([^b]*b){2}	# any non-b, then b, look for it twice
      )*		# look for couplet any # of times
      [^b]*		# any non-b
      $			# then end of string
    )
  /x;			# x for these comments

If there any adjustments that should be made, let me know.  I think it
works fine.

-- 
jeff pinyan    japhy@pobox.com
perl stuff     japhy+perl@pobox.com
CPAN ID: PINYAN            http://www.perl.com/CPAN/authors/id/P/PI/PINYAN


==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe