Strip all punctuation from a string in VB.net

北战南征 提交于 2019-12-05 04:35:54

问题


How do I strip all punctuation from a string in vb.net? I really do not want to do stringname.Replace("$", "") for every single bit of punctuation, though it would work.

How do i do this quickly and efficiently?

Other than coding something that codes this for me....


回答1:


You can use a regular expression to match anything that you want to remove:

str = Regex.Replace(str, "[^A-Za-z]+", String.Empty);

[^...] is a negative set that matches any character that is not in the set. You can just put any character there that you want to keep.




回答2:


Quick example using a positive regex match. Simply place the characters you want removed in it:

          Imports System.Text.RegularExpressions
          Dim foo As String = "The, Quick brown fox. Jumped over the Lazy Dog!" 
          Console.WriteLine(Regex.Replace(foo,"[!,.\"'?]+", String.Empty))



回答3:


If you want a non-regex solution, you could try something like this:

Dim stringname As String = "^^^%%This,,,... is $$my** original(((( stri____ng."

Dim sb As New StringBuilder
Dim c As Char

For Each c In stringname
    If Not (Char.IsSymbol(c) OrElse Char.IsPunctuation(c)) Then
        sb.Append(c)
    End If
Next

Console.WriteLine(sb.ToString)

Output is "This is my original string".



来源:https://stackoverflow.com/questions/1355215/strip-all-punctuation-from-a-string-in-vb-net

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