簡體   English   中英

如何為 VBA 調整正則表達式模式

[英]How can I adapt a regex pattern for VBA

我正在嘗試使用正則表達式刪除特定的文本字符串,並具有以下適用於 regex101.com 但是我知道 VBA 在使用正則表達式時有一些細微差別,而我的模式似乎根本不起作用。

我驗證的模式在下面的代碼中,如果可能的話,我還想將它與下面的代碼結合起來(旨在刪除 html 標簽)“\<.*?>”這確實有效,但我目前運行一個單獨的 regex.replace function 刪除它。

Dim regEx As Object , str As String
Set regEx = CreateObject("VBScript.RegExp")

With regEx
  '.Pattern = "<a\b([^>""']|""[^""]*""|'[^']*')+class=""changed-by"">.*?<\/a>"
'.pattern = "\<.*?\>" ' this is the second pattern i use to remove html tages which works
  .Global = True 'If False, would replace only first
  .IgnoreCase = False
  .MultiLine = False
End With

str = some text here <a href="/instrument/2014/36.pdf" target="_blank" title="2014/36 - 01/07/2014" class="changed-by">1</a> some text here
Debug.Print regEx.Replace(str, "")

如果您要使用Replace function,我認為您需要一些 output 參數,將您找到的內容替換為""將始終返回"" 這就是我想出的,我不確定 Regex 是否真的比你的更好,但它適用於 VBA。 主要區別是我添加的第一個和最后一個組以提取所有文本。

Dim RegEx As New RegExp
Dim Value As String

RegEx.IgnoreCase = True
RegEx.Pattern = "(.*?)<a\b(?:""[^""]*?""|'[^']*?'|[^>]*?)+>([^<]*?)<\/a\b.*?>(.*)"
Value = "some text here <a href=""/instrument/2014/36.pdf"" target=""_blank"" title=""2014/36 - 01/07/2014"" class=""changed-by"">1</a> some text here"
Debug.Print RegEx.Replace(Value, "$1$2$3")

另一個選項是您只需使用Execute function 並將文本從相應的組中拉出。

Dim Col As MatchCollection
Dim i As Long
Set Col = RegEx.Execute(Value)
With Col
    For i = 0 To .Count - 1
        With .Item(i)
            Debug.Print .SubMatches(0) & .SubMatches(1) & .SubMatches(2)
        End With
    Next
End With

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM