Regex help! Thanks so much!

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

Moderator: General Moderators

Post Reply
gullit
Forum Newbie
Posts: 3
Joined: Sat Jul 22, 2006 3:01 am

Regex help! Thanks so much!

Post by gullit »

I am currently using some regex for validation on a text field in JSP.

However, special characters like \ " will make the JSP returns error.

Now I want to write a regex to disallow user input such special characters.

This is what I write

[a-zA-Z0-9,;:<>?/~!@#$%`()-_=+.^&]

however, user still able to input \
why is it so? I think my regex must be wrong, thanks for correction identifications!!!

THANK YOU ALL SO MUCH!!!
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

is this pcre or posix regexp?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Pseudo since I don't do JSP:

Code: Select all

if ( string.match(/^[^\\%\$\"\'\^\*]+$/) )
{
    //All OK
}
Obviously you need to keep adding the characters you want to disallow. It may be easier to only "allow" certain characters. For example:

Code: Select all

if ( string.match(/^[\w\s\.,;:\!\?&]+$/) )
{
    //All OK
}
Notice that I escape lots of characters with a backslash because they already have a special meaning in regex. Also note the use of caret "^" in my first example at the start of the square brackets: [^ ]. The caret in those brackets negates the list of characters inside it.

Notice also the caret "^" and dollar "$" at the start and end of the entire pattern in both my examples. These make sure that the pattern matches the entire string from start to end.
gullit
Forum Newbie
Posts: 3
Joined: Sat Jul 22, 2006 3:01 am

Post by gullit »

Thank you so much!
Your syntax works fine! :wink:
gullit
Forum Newbie
Posts: 3
Joined: Sat Jul 22, 2006 3:01 am

Post by gullit »

Oh! Sorry! I tried this pattern:
if ( string.match(/^[^\\%\$\"\'\^\*]+$/) )
{
//All OK
}
It even doesn't allow brackets like [],{}....
Isn't that the above string regex only disallow characters like %,$,",etc?

Any ideas? Thank you so much!
Post Reply