正则expression式在Excel中使用Visual Basic函数进行匹配和replace

我期待在Excel(2010,Visual Basic 7)中创build一个名为CODEMATCH的用户定义函数

1. Take a range as an input 2. Preserve the structure of the range when outputting 3. On each value in the range: a. If the value matches [matchPattern]: i. regex match the value against [matchPattern] and store it as [var1] ii. regex replace [var1] against [stripPattern] and store it as [var2] iii. return [var2] b. If the value does not match [matchPattern]: i. return an empty value Where matchPattern = "^[^A-Z0-9:]*[A-Z0-9][^A-Z0-9:]*[A-Z0-9]?" stripPattern = "[^A-Z0-9]*" AndWhere RegEx match is not global and respects case RexEx replace is global and respects case Such that "Nobody Cares about Bob" returns "NC" "1 Duck for Jody" returns "1D" "Apples: I Don't Like Them" returns "A" "foobar" returns "" 

我的痛苦的一部分是,我是新来的Visual Basic。 我认为,我的一部分痛苦来自Visual Basic中存在的RegEx的多个版本,不知道哪个版本需要哪些属性。

我试图在复杂程度上构build这个function,而且在我碰到一个不可逾越的砖墙之前,

 Function CODEMATCH(ByVal valueIN As String) As String Set matchRegEx = New RegExp matchRegEx.Pattern = "(sdi \d+)" '<--what's giving me difficulty matchRegEx.Global = False matchRegEx.IgnoreCase = False Set matches = matchRegEx.Execute(valueIN) If matches.Count <> 0 Then CODEMATCH = matches.Item(0).SubMatches.Item(0) Else CODEMATCH = "" End If End Function 

代码是matchPattern ,但它不会让我使用我之前定义的matchPattern 。 除此之外,我仍然需要采用它来执行正则expression式replace,并采用它来处理范围而不是单个单元格。

这怎么样? 🙂

 Function CODEMATCH(ByVal valueIN As String) As String Dim strTemp As String Set matchRegEx = New RegExp With matchRegEx .Pattern = "[^A-Z0-9:]*[A-Z0-9][^A-Z0-9:]*[A-Z0-9]?" .Global = False .IgnoreCase = False If .Test(valueIN) Then Set matches = .Execute(valueIN) .Pattern = "[^A-Z0-9]*" .Global = True strTemp = matches(0) CODEMATCH = .Replace(strTemp, vbNullString) Else CODEMATCH = vbNullString End If End With End Function 

testing

 Sub Test() Debug.Print CODEMATCH("Nobody Cares about Bob") Debug.Print CODEMATCH("1 Duck for Jody") Debug.Print CODEMATCH("Apples: I Don't Like Them") Debug.Print CODEMATCH("foobar") End Sub