Skip to main content
Inspiring
February 12, 2010
Question

regex & Special Characters

  • February 12, 2010
  • 2 replies
  • 8235 views

I needed a quick means of limiting characters in user-provided form data throughout my application, so I came up with the following regex script which can be modified on a per-field basis for whatever characters I want a given field to support. As a point of reference I wanted to start by coming up with a default, or a means of allowing standard characters that might appear in an English string, but I'm having a little problem. Here is what I came up with:

<CFIF refind("[^A-Za-z0-9!\@\##\$%\&\*-_\+:',\?\./]", form.variable_name, 1) GT 0>

...code to execute here...

</CFIF>

This regex script essentially allows for letters, numbers, and: ! @ # $ % & * - _ + : ' ? . /

In testing this, I tried entering various special characters, and in all cases I tested the regex script caught anything not in my list.

That is, until I used the "^" symbol. That flew right through. Then I discovered "[" and "]" did too. If these were, who knows what else would?

So that brings me here. I am not a fan of writing regex scripts, do it so infrequently, and thus are not very savvy at it.

Am I doing something wrong? Is there a better way to do this perhaps?

    This topic has been closed for replies.

    2 replies

    Inspiring
    February 13, 2010

    This threw me for a bit.

    You're not escaping your -, so the regex engine is treating "*-_" as a range.  So everything from ASCII 42 to ASCII 95 - which includes those special characters mention - will match.

    --

    Adam

    Inspiring
    February 23, 2010

    I recommend checking out the software package The RegEx Coach (http://weitz.de/regex-coach/).  It provides a simple, great interface for writing and testing regular expression patterns.  Using something like that should allow you to see visually that your problem is.

    Inspiring
    February 12, 2010

    Try using FindOneOf.