在Excel中像使用函数一样优雅的使用正则表达式
"-hz" '删除汉字
"-zm" '删除字母
"-sz" '删除数字
"+hz" '提取汉字
"+zm" '提取字母
"+sz" '提取数字
=INDEX(RegFun($A2,"(-?\d+)(\.\d+)?"),COLUMN(A1))
(-?\d+)(\.\d+)? : 用于匹配浮点数
[\u4e00-\u9fa5] :表示汉字
?=\d :在目标文本中,只有数字前面的汉字才会得到匹配()
'作者:小易
'公众号:Excel办公实战
'功能:正则表达式简易封装
'-------------------------------------------------------
Function RegFun(str As String, sPattern As String, _
Optional bType As Boolean = True, _
Optional bGlobal As Boolean = True, _
Optional bMultiLine As Boolean = False, _
Optional bIgnoreCase = False)
Dim oReg As Object, oMatches As Object
Dim arr(), i As Long, oMatch As Object
Set oReg = CreateObject("VbScript.RegExp")
With oReg
.Global = bGlobal
.MultiLine = bMultiLine
.IgnoreCase = bIgnoreCase
If bType Then
.Pattern = sPattern
Set oMatches = .Execute(str)
If oMatches.Count > 0 Then
For Each oMatch In oMatches
i = i + 1
ReDim Preserve arr(1 To i)
arr(i) = oMatch.Value
Next
RegFun = arr
Else
RegFun = ""
End If
Else
Select Case sPattern
Case Is = "-hz" '去汉字
.Pattern = "[一-﨩]"
Case Is = "-zm" '去字母
.Pattern = "[a-zA-Z]"
Case Is = "-sz" '去数字
.Pattern = "[0-9\.]"
Case Is = "+hz" '取汉字
.Pattern = "[^一-﨩]"
Case Is = "+zm" '取字母
.Pattern = "[^a-zA-Z]"
Case Is = "+sz" '取数字
.Pattern = "[^0-9\.]"
End Select
RegFun = .Replace(str, "")
End If
End With
End Function
本文由“壹伴编辑器”提供技术支持