Question

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.

Was it helpful?

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.

OTHER TIPS

ColdFusion uses Java's engine to parse regular expressions, anyway to make sure a string doesn't contain one of the characters you mentioned then try:

^(?![a-zA-Z0-9 ,.&$']*[^a-zA-Z0-9 ,.&$']).*$

The above expression would only work if you are parsing the file line by line. If you want to apply this to text which contains multiple lines then you need to use the global modifier and the multi-line modifier and change the expression a bit like this:

^(?![a-zA-Z0-9 ,.&$']*[^a-zA-Z0-9 ,.&$'\r\n]).*$

Regex101 Demo

The regular expression:

[^][a-zA-Z0-9 ,.&'$]

will match if the string contains any characters other than the ones in your list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top