VBA如何提取并返回字符串中匹配到的特殊字符(附现有代码)
调整方案
核心调整逻辑:把原有的替换逻辑改为调用正则对象的Execute方法获取所有匹配结果,遍历匹配集合即可提取到所有命中的特殊字符。
调整后可直接运行的代码
Function getMatchedSpecialCharacters(theString As String) As String Dim StrTest As String Dim Result As String Dim Reg1 As Object Dim matches As Object Dim match As Object StrTest = theString Set Reg1 = CreateObject("VBScript.RegExp") With Reg1 .Global = True .IgnoreCase = True .Pattern = "[-[\]{}()%*+?\\/^$|#\s]" ' 特殊字符匹配规则 End With If Reg1.Test(StrTest) Then ' 获取所有匹配结果集合 Set matches = Reg1.Execute(StrTest) ' 遍历所有匹配项拼接为结果 For Each match In matches Result = Result & match.Value Next End If getMatchedSpecialCharacters = Result End Function
补充说明
- 如果需要返回去重后的特殊字符,只需要在拼接前判断当前字符是否已经存在于Result中即可,示例逻辑:
If InStr(Result, match.Value) = 0 Then Result = Result & match.Value End If
- 如果既要返回替换后的字符串,又要返回匹配到的特殊字符,可以把函数修改为返回数组,或者用传址参数输出匹配结果。
内容的提问来源于stack exchange,提问作者pokemon_Man
相关产品推荐
相关产品推荐

