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

Re: [FWP] counting in REs



>>>>> "RM" == Rich Morin <rdm@cfcl.com> writes:

  RM> A friend of mine recently presented me with three cases to match with
  RM> a regular expression:

  RM>    1)  test for an even number of 'a's in a string

  RM>    2)  test for an odd  number of 'b's in a string

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

  RM> Tasks 1 and 2 are pretty easy.  Task 3, however, is rather tricky.  I
  RM> will post some possible approaches in a followup...

as ronald said, the first wo are the same and not so hard:


<SPOILER SPACE>


















































perl -lne 'print if /^(?:[^a]*a[^a]*a)+[^a]*$/'

expanded:

	/^(?:		# non grabbinf group

		[^a]*	# 0 or more non a's (prefix)
		a	# first 'a' of even pair
		[^a]*	# 0 or more non a's (separater)
		a	# second 'a' of even pair
		)+	# multiple pairs of a's (with optional prefix
			# and separator
		[^a]*	# optional trailing non a's
	$/		# end of string (or before newline)


b is exactly the same.

to check for both, use a lookahead with a and another with b:

 perl -lne 'print if /^(?=(?:[^a]*a[^a]*a)+[^a]*$)(?=(?:[^b]*b[^b]*b)+[^b]*$)/'

seems to work fine for me. i haven't hammered it but my test cases pass.

uri


-- 
Uri Guttman  -----------------  SYStems ARCHitecture and Software Engineering
uri@sysarch.com  ---------------------------  Perl, Internet, UNIX Consulting
Have Perl, Will Travel  -----------------------------  http://www.sysarch.com
The Best Search Engine on the Net -------------  http://www.northernlight.com
"F**king Windows 98", said the general in South Park before shooting Bill.

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