[thelist] RegEx problem again

Matt Warden mwarden at gmail.com
Mon Aug 8 11:26:39 CDT 2005


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Tom Dell'Aringa wrote:
> Last week you all helped me with a regex I thought I had licked, but turns up there is a problem.
> I can't quite figure it out as usual. To refresh, I have a customer name field that requires:
> 
> - Minimum 3 characters
> - Only alpha characters
> - Can include a wildcard character of '*' (in which case you would require 4 characters)
> 
> To that end I had this:
> 
> var namematch = /^[a-zA-Z]{3,}$/.test(nametext.value);
> namematch = (namematch  || /^[a-zA-Z\*]{4,}$/.test(nametext.value));
> 
> Which worked just fine, till we realized we need to allow one or more SPACES as well! How do you
> add a space to the pattern? (and allow for as many spaces as they like?)

That complicates things a good bit. Personally, when testing the
input, I would simply strip spaces first.

However, since my brain could use a little excercise, let's give it a
shot.

/^[a-z\*][\s]*[a-z\*][\s]*[a-z\*][\s]*[a-z\*]+[\s]*[a-z\*]*$/i

That will give you 4 or more alpha characters (plus *) with any number
of spaces in between (except at the beginning, which isn't allowed by
the regex).

The problem is that this doesn't fit your requirement of allowing 3
characters if * isn't present. (watch line wrap)

/^([a-z][\s]*[a-z][\s]*[a-z][\s]*)|([a-z\*][\s]*[a-z\*][\s]*[a-z\*][\s]*[a-z\*]+[\s]*[a-z\s\*]*)$/i

This first part allows for 3 alpha characters with any number of
spaces anywhere in the string (except beginning).

Failing that, it allows for 4 or more alpha characters (plus *) with
any number of spaces in between (except beginning).

So, if the first condition doesnt match and teh second does, then we
can assume that there is either a * in the string or the length is
>= 4 characters (minus spaces).

I believe the regex can be condensed thusly:

/^([a-z][\s]*){3}|(([a-z\*][\s]*){4}[a-z\s\*]*)$/i

hth,

- --
Matt Warden
Miami University
Oxford, OH, USA
http://mattwarden.com


This email proudly and graciously contributes to entropy.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFC94e+AQ0d4HGyPE8RAgGRAJ9j4lHlu+1YUvgbJecdqI/lr/C7SQCdH66/
SDtfE43KBH4jMy8A1ZPYf/8=
=WUFV
-----END PGP SIGNATURE-----


More information about the thelist mailing list