正则表达式 - Excel - 获取匹配的值


0

我正在寻找一些建议。

我正在尝试在Visual Basic for Excel中使用正则表达式(参考已设置的Microsfot VBScript正则表达式5.5)。

我只想要这个函数来测试我的正则表达式 \d\d\d\d\d (查找任何5个连续的整数)如果是,则给出匹配的值。

例如,如果我有字符串“aaaaa 12345 bbb”,我希望函数给出“12345”。看似简单,但......不适合我。

到目前为止这是我的代码:

Function EXTRACT_CP(cell_with_text As Range) As String

Dim regEx As New RegExp
Dim strexpresion As String
Dim strInput As String
Dim strReplace As String
Dim strOutput As String

strexpresion = "\d\d\d\d\d"
strInput = UCase(cel_with_text.Value)

  regEx.Pattern = strexpresion

  If regEx.Test(strInput) Then

‘THIS LINE OBVIOUSLY FAILS BUT I DON’T KNOW WHAT TO PUT
        strOutput = regEx.Replace(strInput, "\d\d\d\d\d")

  End If

EXTRACT_CP = strOutput

End Function

只想知道如何获得任何正则表达式的匹配值。


Answers:


1

连续五位数?

添加变量:

Dim colMatches As Object
Dim ix As Long
Dim separator As String

有效的RegEx:

regEx.Pattern = "(\d{5})"

更改:

strOutput = regEx.Replace(strInput, "\d\d\d\d\d")

至:

Set colMatches = regEx.Execute(strInput)

并迭代你唯一的比赛 (\d{5})colMatches.Item(0) 对于子匹配:

separator = "|"
strOutput = ""
For ix = 0 to colMatches.Item(0).submatches.count - 1
  strOutput = strOutput + colMatches.Item(0).submatches.Item(ix) + separator

编写代码时没有VBA编辑器,因此可能需要进行调整。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.