文本提取處理領域,正則表達式是最為強大的存在,工作中Excel 是常用的小型數據采集,處理,分析的工具但本身不具備正則的能力,讓Excel擁有正則的能力無疑是如虎添翼的能力。
方案
讓正則作為函數內容的一部分,給這類業務正則直接命名一個函數名稱,調用時直接訪問和Excel 系統函數一樣簡單
函數自定義
RegexExtract(rng As Range, ByVal Pattern As String, Optional MatchIndex As Integer = 0, Optional IgnoreCase As Boolean = True)
參數名稱 | 簡介 |
---|---|
rng | 需要提取文本的單元格 |
Pattern | 正則表達式規則字符串,備注:用戶根據場景自定義,比如\d+,表示提取連續字符串 |
MatchIndex | 單元格中匹配成立的字符串集合中,取第幾個,起始索引為 0,默認為 0 |
IgnoreCase | 匹配規則屬性設置,是否區分大小寫,True 區分,False 不區分 |
Function Code
' 提取字符串中符合正則規則的內容
Function RegexExtract(rng As Range, ByVal Pattern As String, Optional MatchIndex As Integer = 0, Optional IgnoreCase As Boolean = True) As String' on error resume nextDim regEx As Object, matches As ObjectSet regEx = CreateObject("VBScript.RegExp")With regEx.Pattern = Pattern.IgnoreCase = IgnoreCase.Global = TrueEnd WithSet matches = regEx.Execute(rng.Value)If matches.Count > 0 ThenIf MatchIndex < 0 Or MatchIndex >= matches.Count ThenRegexExtract = "Index out of range"ElseRegexExtract = matches(MatchIndex).ValueEnd IfElseRegexExtract = "No match"End IfSet regEx = NothingEnd Function