Page 1 of 1
Regex help! Thanks so much!
Posted: Sat Jul 22, 2006 3:05 am
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!!!
Posted: Sat Jul 22, 2006 7:35 am
by Weirdan
is this pcre or posix regexp?
Posted: Sat Jul 22, 2006 7:41 am
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.
Posted: Sun Jul 23, 2006 8:12 pm
by gullit
Thank you so much!
Your syntax works fine!

Posted: Sun Jul 23, 2006 9:31 pm
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!