Alter code to Remove instead of Allow characters

时光总嘲笑我的痴心妄想 提交于 2019-12-24 17:53:20

问题


The function allows the character listed (in this case)

Case 48 To 57, 65 To 90, 97 To 122:

Is it possible to change this to Remove the characters listed instead?

Thanks

Function AlphaNumericOnly(strSource As String) As String
    Dim i As Integer
    Dim strResult As String

    For i = 1 To Len(strSource)
        Select Case Asc(Mid(strSource, i, 1))
            Case 48 To 57, 65 To 90, 97 To 122:
                strResult = strResult & Mid(strSource, i, 1)
        End Select
    Next
    AlphaNumericOnly = strResult
End Function

回答1:


If you intend to use For ... Next - just add Case Else:

    For i = 1 To Len(strSource)
        Select Case Asc(Mid(strSource, i, 1))
            Case 48 To 57, 65 To 90, 97 To 122:
            Case Else:
                strResult = strResult & Mid(strSource, i, 1)
        End Select
    Next

As @pnuts pointed and @brettdj answered - RegEx is more efficient, in your case the function may be as follows:

Function NonAlphaNumericOnly(strSource As String) As String
    With CreateObject("VBScript.RegExp")
        .Global = True
        .IgnoreCase = True
        .Pattern = "[\w]+"
        NonAlphaNumericOnly = .Replace(strSource, "")
    End With
End Function


来源:https://stackoverflow.com/questions/32192616/alter-code-to-remove-instead-of-allow-characters

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