need some help with matching alpha-num with some punctuation

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

need some help with matching alpha-num with some punctuation

Post by Luke »

I am really terrible at regex. I have an O'Reilly regex book on my wishlist, but for now, can somebody help me put together a regular expression to match 1 or more of alpha-numeric characters and allow also these characters: /,.-&'

here is what I have... and it doesn't work

Code: Select all

'/^[a-zA-Z0-9/\,\.-&\']+$/'
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

RegExpLib

EDIT | Are there any other contraints? Like having to start with a letter, not with a number or special char, etc.

EDIT 2 | Try this one...

Code: Select all

[A-Z0-9a-z\'\%\\\\\&]
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

Code: Select all

$regex = '#[a-z0-9/,\.\-&\']+#i';
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

Oren wrote:

Code: Select all

$regex = '#[a-z0-9/,\.\-&\']+#i';
I tried this one above, but it allows the following to get through...
Luke's the !@#$^ Coolest guy ever!

I imagine it's because it's matching the first letter and returning true... I should clarify... it's for a form field... so it has to match the entire string.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

What are the requirements, completely. Spaces, no spaces, start with something special, length, etc?
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

Everah wrote:What are the requirements, completely. Spaces, no spaces, start with something special, length, etc?
spaces are ok... doesn't need to start with anything special... 45 characters (although length is not strictly necessary)
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Code: Select all

$pattern = '#^[a-zA-Z0-9\s.\-\&\/\,\\\']+$#';
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

If spaces are fine and it's for form validation then use this:

Code: Select all

$regex = '#^[a-z0-9/,\.\-&\'\s]+$#i';
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Very nice. I forget sometimes about the case insensitive 'i' flag.
Post Reply