0

I am trying to achieve the following using regex in C# in .Net application

I need to restrict strings which contains 'ONLY' these three special characters namely #,@ and %. Any other character is allowed

some examples

ab#c - allowed

abc#@ - allowed

#%abc - allowed

#@% - not allowed

##@ - not allowed

What I tried ^(?!(#|@|%)+$) But it doesn't seem to work as expected. Where am I going wrong ?

I am using data annotations on the property, so I am looking for a regex pattern that can exclude the incorrect input strings. I cannot use the Regex.IsMatch() function.

Clarification: My string should accept any characters. The only case it should fail is when the input string only has #,@ or %.

wickjon
  • 900
  • 5
  • 14
  • 40

1 Answers1

0

This isn't elegant but does the job I think: ^[\w#@%]*\w+[\w#@%]*$

screen shot

Works for your examples

I'm taking "non-special" characters to mean \w.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
Chris D
  • 102
  • 1
  • 7