在 excel 中启用正则表达式
Mar 29, 2021 • 🍻 01min 42s read
🔖 exceltools
Usage
¶启用 VBA (
*.xlsm
文件中有效)- 在 Excel 中:
文件
-->选项
-->自定义功能区
勾选开发工具
- 在 Excel 中:
启用 Microsoft VBScript Regular Expressions5.5 模块
- 打开 Visual Basic 编辑器:
开发工具
-->Visual Basic
- 在 Visual Basic 编辑器中打开:
工具
-->引用
- 在弹出的对话框中勾选
Microsoft VBScript Regular Expressions 5.5
- 打开 Visual Basic 编辑器:
导入正则表达式的 VBA 脚本
在 Visual Basic 编辑器中打开
插入模块
(文件选项卡的正下方) -->模块
在弹出的对话框中粘贴如下脚本:
regex.vb1234567891011121314151617181920212223242526272829303132333435363738394041424344454647Function regex(strInput As String, matchPattern As String, Optional ByVal outputPattern As String = "$0") As VariantDim inputRegexObj As New VBScript_RegExp_55.RegExp, outputRegexObj As New VBScript_RegExp_55.RegExp, outReplaceRegexObj As New VBScript_RegExp_55.RegExpDim inputMatches As Object, replaceMatches As Object, replaceMatch As ObjectDim replaceNumber As IntegerWith inputRegexObj.Global = True.MultiLine = True.IgnoreCase = False.Pattern = matchPatternEnd WithWith outputRegexObj.Global = True.MultiLine = True.IgnoreCase = False.Pattern = "\$(\d+)"End WithWith outReplaceRegexObj.Global = True.MultiLine = True.IgnoreCase = FalseEnd WithSet inputMatches = inputRegexObj.Execute(strInput)If inputMatches.Count = 0 Thenregex = FalseElseSet replaceMatches = outputRegexObj.Execute(outputPattern)For Each replaceMatch In replaceMatchesreplaceNumber = replaceMatch.SubMatches(0)outReplaceRegexObj.Pattern = "\$" & replaceNumberIf replaceNumber = 0 ThenoutputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).Value)ElseIf replaceNumber > inputMatches(0).SubMatches.Count Then'regex = "A to high $ tag found. Largest allowed is $" & inputMatches(0).SubMatches.Count & "."regex = CVErr(xlErrValue)Exit FunctionElseoutputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).SubMatches(replaceNumber - 1))End IfEnd IfNextregex = outputPatternEnd IfEnd Function保存,然后关闭各种对话框
使用
直接选中单元格,然后在上面输入公式即可,语法如下:
1regex(<original_string>, <regex_pattern>, <replace_string>)<original_string>
原始字符串,可以使用 Excel 中的单元格引用,如E4
<regex_pattern>
正则表达式,无需转义,如:"(\d+)\.(\d+)\.(\d+)"
<replace_string>
替换的字符串,如:"$1年$2月$3日"
Related
¶