From: "Mariusz Pękala" Date: 2007-06-22T19:55:02+09:00 Subject: Re: Do You Understand Regular Expressions? --k+w/mQv8wyuph6w0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On 2007-06-21 23:12:32 +0900 (Thu, Jun), Rob Biedenharn wrote: > On Jun 21, 2007, at 9:47 AM, Stephen Ball wrote: > >It's because the pattern /.*/ matches everything, including the > >absence of everything. Yes, with the proper regexs you can indeed have > >tea and no tea at the same time. Certainly peculiar, but occasionally > >useful. >=20 > That still doesn't really explain why "hello".scan(/.*/) =3D> ["hello", = =20 > ""] >=20 > Why wouldn't it be ["hello", "", "", "", "", "", "", "", "", "", "", =20 > "", ... ] since I (or rather the OP) could continue to match zero =20 > characters (bytes) at the end of the string forever? It does seem =20 > that it might be that a termination condition is checked a bit later =20 > than it should be in this case. I would say the condition is checked at the right time, it's just the condition is different: it allows checking a match for empty string at the end of just-matched string, it does not allow checking empty string after ampty string. The interesting behaviour is: irb(main):035:0> "hello".scan /.*?/ =3D> ["", "", "", "", "", ""] The /.*?/ matches 'zero or more characters, preferring the shortest match'. One could ask - where have the actual characters gone? Note that it's not an infinite loop of empty strings. After matching 'nothing', the start-position for next match is increased, skipping one character, to prevent infinite loop of matching nothing again. *This* behavour may be considered weird, or buggy, and probably results are not what was expected. But look at: irb(main):038:0> "hello".scan /h(.*)e/ =3D> [[""]] irb(main):039:0> "hello".scan /h(.*)(.*)(.*)(.*)(.*)e/ =3D> [["", "", "", "", ""]] Here 'nothing' matches many times, and definitely this *is* the expected behaviour. --=20 No virus found in this outgoing message. Checked by 'grep -i virus $MESSAGE' Trust me. --k+w/mQv8wyuph6w0 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7-ecc0.1.6 (GNU/Linux) iD8DBQFGe6qIsnU0scoWZKARAinZAJ90/W0QbLmoCRwEPshaOTxsvxohRgCeLM0E to5oOEBI6bj7NtbiSky/d+c= =04Fg -----END PGP SIGNATURE----- --k+w/mQv8wyuph6w0--