vb.net vb.net中如何检查字符串是否包含特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48862008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check whether the string contains special characters or not in vb.net?
提问by user9379730
I want to check whether the input contains special characters(@"[~`!@#$%^&*()-+=|{}':;.,<>/?]") or not in vb.net?
我想在 vb.net 中检查输入是否包含特殊字符(@"[~`!@#$%^&*()-+=|{}':;.,<>/?]") ?
How can I check that in vb.net code?
如何在 vb.net 代码中检查?
回答by MatSnow
If you want to check if any of the mentioned characters are contained in the string you can use the following function:
如果要检查字符串中是否包含任何提到的字符,可以使用以下函数:
Function ContainsSpecialChars(s As String) As Boolean
Return s.IndexOfAny("[~`!@#$%^&*()-+=|{}':;.,<>/?]".ToCharArray) <> -1
End Function
Or if you want to check if the string just contains letters, digits or whitespace, you can use the following function:
或者,如果您想检查字符串是否只包含字母、数字或空格,您可以使用以下函数:
Function ContainsSpecialChars(s As String) As Boolean
Return s.Any(Function(c) Not (Char.IsLetterOrDigit(c) OrElse Char.IsWhiteSpace(c)))
End Function
回答by Tim Schmelter
If the string can only contain letters or digits(0-9) or white-spaces:
如果字符串只能包含字母或数字(0-9)或空格:
Dim noSpecialCharacters = text.
All(Function(c) Char.IsLetterOrDigit(c) OrElse Char.IsWhiteSpace(c))
Dim containsSpecialCharacters = Not noSpecialCharacters

