string 如何检查字符串中的字符、数字和特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4760659/
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 can i check for character , number and special characters in a string?
提问by Preeti
I want to user to enter only numbers and characters in textbox i.e no special charaters. I don't want to use key press event of textbox.
我想让用户在文本框中只输入数字和字符,即没有特殊字符。我不想使用文本框的按键事件。
As i need same validation in gridview.
因为我需要在 gridview 中进行相同的验证。
So i want to validate whole string.
所以我想验证整个字符串。
Thanks in advance.
提前致谢。
回答by Joel Etherton
Using the Regex class for regular expressions you can use:
将 Regex 类用于正则表达式,您可以使用:
If Regex.IsMatch(myString, "^[A-Za-z0-9]+$") Then
'Do stuff
End If
EDIT: I forgot to add the ^
and the $
to denote that the match should go from start to finish on the string. You'll also need to put a \s
in there if whitespace is allowed.
编辑:我忘了添加^
和$
来表示匹配应该在字符串上从头到尾进行。\s
如果允许空格,您还需要在那里放一个。
回答by Saggio
You can parse the string and then check the ascii values to make sure they are only Alpha-numeric. Here's some pseudocode:
您可以解析字符串,然后检查 ascii 值以确保它们只是字母数字。这是一些伪代码:
StrLength = Len(Text)
For x = 1 To StrLength
sChar = Mid$(Text, x, 1)'Gets the x'th charcter in Text
bASCII = Asc(sChar) 'Gets ASCII value of character
if bASCII(not in Range) Then ERROR
Next x
Here's a link for to the Ascii Values: http://www.asciitable.com/
这是 Ascii 值的链接:http: //www.asciitable.com/