-2

I need a regular expression pattern to verify string does not contain only white spaces(blank with multiple space only)(Ex: " ".length = 4) and should not contain !@$#%^&*() characters.

Regex regex = new Regex(@".\S+."); This one checks for white spaces. I need both condition in one Regex pattern.

   Result
   ---------
  • " " : false
  • "ad af" : true
  • " asd asd " : true
  • " asdf " : true
  • "asdf@df dsfs " : false
  • " # " : false
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Sipun
  • 11
  • 5
  • 1
    What code do you have so far? – Stormhashe Feb 19 '19 at 19:03
  • Kindly refer to this answer: [How do I not allow special characters, but allow space in regex?](https://stackoverflow.com/questions/14106109/how-do-i-not-allow-special-characters-but-allow-space-in-regex) – Muqadar Ali Feb 19 '19 at 19:09
  • [RegularExpression(@"^[^~!@#$%&*]+$", ErrorMessage = "Given value is not correct")] . This checks for special characters but i need to check for spaces (textbox contains only spaces). – Sipun Feb 20 '19 at 05:21
  • Both condition in one regular expression – Sipun Feb 20 '19 at 07:16

2 Answers2

2

As a single regex:

!Regex.IsMatch(input, "^\s+$|[!@$#%^&*()]");

This means:

^\s+$        //Is entirely composed of one or more whitespace characters 
|            //OR
[!@$#%^&*()] //Contains any one of the given special characters

This regex returns the opposite of the truth you want (i.e. it looks for anything that is all whitespace OR does contain a special char), so we NOT it with ! to match your requirements

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
  • I required in RegularExpression[RegexPattern] annotation in .net MVC model. So I need a pattern that does return false if condition not satisfies. Its not possible to give NOT with !. – Sipun Feb 20 '19 at 03:59
0

If you are looking for a regex for "only alphabets with space in between" you can use this:

[a-zA-Z][a-zA-Z ]+

If you want allow, numbers also, use this:

[a-zA-Z0-9][a-zA-Z0-9 ]+
Sahi
  • 1,454
  • 1
  • 13
  • 32