Forum Moderators: coopster

Message Too Old, No Replies

Regular Expressions help

My regular expression isn't working

         

The_Warden

4:49 pm on May 12, 2006 (gmt 0)

10+ Year Member



I do admit I'm not quite at the level to full understand how I would create an expression I require. Right now I'm trying to create a regular expression that checks to see a given string (case insensitive) only contains alpha characters (a-z), spaces, punctuations ('), periods, hyphens and numeric characters (unsigned 0-9) in no particular order. If the string contains anything else other then what I said it should fail the check. This is what I have below so far but it's not working for me.

/^[A-Za-z[:space:][:punct:][0-9]\.\-]+$/

Thanks!

jezra

5:52 pm on May 12, 2006 (gmt 0)

10+ Year Member



I would try taking the numeric value out of the brackets.
/^[A-Za-z[:space:][:punct:]0-9\.\-]+$/
you should be able to shorten the pattern by converting A-Za-z0-9 to [:alnum:] and removing the period and hyphen as they are part of [:punct:]

/^[[:alnum:][:space:][:punct:]]+$/

Do you have a test string that should fail to match?

coopster

6:29 pm on May 12, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member




If the string contains anything else other then what I said it should fail the check.

Right now you are telling it to allow anything that at least starts with (^), ends with ($) and includes at least one of (+) those characters found in the character class (stuff in between the brackets). The way it is written you will allow the string to include any OTHER character that you don't want as well.

The correct way to do this is to put the *good* characters in your class and then negate the whole works. If you get a hit, then you have a problem.

And, as mentioned, first you need to get the brackets off your digits range, you are already inside a character class so you don't want to do that again.

$pattern = "/[^A-Za-z[:space:][:punct:]0-9\.\-]/";

Lastly, I agree, it seems you are allowing any printable character, so why not just use the POSIX print class?