rohit rohit - 2 months ago 8
ASP.NET (C#) Question

Regex to allow only string but not word "test"

^[a-zA-Z'.\s]{2,40}$"
is the original
regex
used for firstname field in my project. I want to modify this
regex
such that it will not allow 'test' As an input.

"^(?!^test$)(^.*$)");"
works fine to exclude word 'test' but it allows spaces & numbers. so what will be the regex which will allow only
string
as an input but will not allow word 'test' i.e. first name may not be 'test' ?

Answer

You may use

^(?!test$)[a-zA-Z'.\s]{2,40}$

See the regex demo.

Details:

  • ^ - start of string
  • (?!test$) - the string cannot equal test
  • [a-zA-Z'.\s]{2,40} - 2 to 40 symbols that are ASCII letters, ', . or whitespace
  • $ - end of string