vb.net 如何从字符串中删除非字母字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20463134/
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 remove non-alphabetical characters from a string?
提问by user3081500
I am looking for a way to remove characters from any string that are not alphabetical characters.
我正在寻找一种方法来从任何不是字母字符的字符串中删除字符。
I am basically just using Replace for every non-Alphabetical character. This method would take forever.
我基本上只是对每个非字母字符使用替换。这种方法需要永远。
I guess I could make an array (I think) but that would still take quite a while. Is there any simple solution?
我想我可以制作一个数组(我认为),但这仍然需要很长时间。有什么简单的解决办法吗?
Dim wordy As String = textBox.Text.ToUpper.Replace(".", "").Replace("!", "").Replace(" ", "").Replace("'", "").Replace("?", "") _
.Replace(",", "").Replace("-", "")
回答by Justin E
The following lines of code should help.
以下代码行应该会有所帮助。
MsgBox(Regex.Replace(s, "[^a-zA-Z ]", ""))
This will keep only upper/lowercase A-Z as well as spaces.
这将只保留大写/小写 AZ 以及空格。
Your example,
你的例子,
Dim wordy As String = textBox.Text.ToUpper.Regex.Replace(s, "[^a-zA-Z ]", "")
You could also just use a MaskedTextBoxthat would allow only numeric input based on the mask.
您也可以只使用一个MaskedTextBox,它只允许基于掩码的数字输入。
回答by damienc88
This will remove all characters except A-Z in lower and upper case, as well as spaces. If you want spaces to be removed, remove the space from the end of the regular expression.
这将删除除 AZ 之外的所有小写和大写字符以及空格。如果要删除空格,请删除正则表达式末尾的空格。
Dim rgx As New Regex("[^a-zA-Z ]")
Dim wordy As String = rgx.Replace(textBox.Text,"")

