Search code examples
regexcoldfusioncoldfusion-8

Regex Check Whether a string contains characters other than specified


How to check whether a string contains character other than:

  • Alphabets(Lowe-Case/Upper-Case)

  • digits

  • Space

  • Comma(,)

  • Period (.)

  • Bracket ( )

  • &

  • '

  • $

  • +(plus) minus(-) (*) (=) arithmetic operator

  • /

using regular expression in ColdFusion?

I want to make sure a string doesn't contain even single character other than the specified.


Solution

  • You can find if there are any invalid characters like this:

    <cfif refind( "[^a-zA-Z0-9 ,.&'$()\-+*=/]" , Input ) >
    
        <!--- invalid character found --->
    
    </cfif>
    

    Where the [...] is a character class (match any single char from within), and the ^ at the start means "NOT" - i.e. if it finds anything that is not an accepted char, it returns true.

    I don't understand "Small Bracket(opening closing)", but guess you mean < and > there? If you want () or {} just swap them over. For [] you need to escape them as \[\]


    Character Class Escaping

    Inside a character class, only a handful of characters need escaping with a backslash, these are:

    • \ - if you want a literal backslash, escape it.
    • ^ - a caret must be escaped if it's the first character, otherwise it negates the class.
    • - - a dash creates a range. It must be escaped unless first/last (but recommended always to be)
    • [ and ] - both brackets should be escaped.