C# string should not contain only white spaces or any special character except ,.';:" [duplicate]

不羁岁月 提交于 2019-12-13 08:56:50

问题


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

回答1:


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




回答2:


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 ]+


来源:https://stackoverflow.com/questions/54773228/c-sharp-string-should-not-contain-only-white-spaces-or-any-special-character-exc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!