我期待在Excel中創建用戶定義的函數在Excel的範圍替換(2010,Visual Basic中7)呼籲CODEMATCH即會正則表達式匹配和使用Visual Basic功能
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的多個版本,並且不知道哪個版本需要哪些屬性。
我試圖建立功能最多的複雜程度,這是據我可以得到我打了一個堅不可摧的磚牆前:
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
。除此之外,我仍然需要採用它來執行正則表達式替換,並採用它來處理範圍而不是單個單元格。
難道只是我,還是會'VAR1 = regex.Match(valueIn,matchPattern); var2 = regex.Replace(var1,stripPattern,「」)'太明顯了? –
爲什麼不把'matchPattern As String'作爲函數的另一個輸入並將它與'matchRegEx.Pattern = matchPattern'一起使用? – TheEngineer
請參閱下文,我使用了兩個步驟的過程,一個用於匹配的Execute和一個用於替換條紋的Replace。不需要submatches – brettdj