-1

Hi I'm trying to ensure text box does not contain any of the following characters:

! @ # $ % ^ & * ( ) < > ‘ ’+ [ ] ? { } | , ; : . “ ~ `

I'm trying to use regular expression with C# server side code: something like the below (but I think my regular expression is wrong):

Regex reg = new Regex(@"^[^\%\/\\\&\?\,\'\;\:\!\+\$#\^\*\(\)\|~]+$");//! @ # $ % ^ & * ( ) < > ‘ ’+ [ ] ? { } | , ; : . “ ~ `
if(!Regex.IsMatch(Textbox_Timetable.Text.Trim(), @"^[^\%\/\\\&\?\,\'\;\:\!\-]+$"))                     
    AddError("Timetable Name must not contain following characters: " + @"\%\/\\\&\?`\,\'\;\:\!\-");
Nico
  • 12,493
  • 5
  • 42
  • 62
rafskiBob
  • 17
  • 3
  • 1
    Now the first question is... Are those **ALL** the characaters you dont want or just the characters you have on your keyboard or do you only wish A-Z, 0-9? – Nico Feb 27 '17 at 06:42

3 Answers3

2

Use the Regex.Escape(...) method if you want readable code:

var escaped = Regex.Escape("!@#$%^&*()<>‘’+[]?{}|,;:.“~`");
var regex = new Regex($"[{escaped}]");

That is so much easier than escaping every character manually!

You should drop the ^ and $ from your regex. You wanted to detect if any of those characters were in the target string, but using those in your regex would mean it would only match if every character was from that list.

(This code hasn't been tested, as I dont have a compiler available)

0
[^\%\/\\\&\?\,\'\;\:\!\+\$#\^\*\(\)\|~]+

^ if is present as first character in square bracket, then it denotes matches any character except following

\%\/\\\&\?\,\'\;\:\!\+\$#\^\*\(\)\|~]

use this

^[\%\/\\\&\?\,\'\;\:\!\+\$#\^\*\(\)\|~^@]+` or `^[\^\%\/\\\&\?\,\'\;\:\!\+\$#\^\*\(\)\|~@]+

to solve.

noufalcep
  • 3,446
  • 15
  • 33
  • 51
Unais U
  • 1
  • 1
  • 1
0

Just grab any char you want [!@#$%^&*()<>‘’+[]?{}|,;:.“~`] and that's your regex. Then simple inversion using !` is all you nead to check if input is vald.

Maciej Kozieja
  • 1,812
  • 1
  • 13
  • 32