萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

VBScript 正則表達式進階:後向引用 實戰去除重複單詞與 URI 解析

後向引用概念

圓括號 (...) 捕獲的子匹配會存入暫存緩衝區,編號 1-99。在模式中用 \1、\2... 反向引用;在替換字串中用 $1、$2...。

實戰 1:去除連續重複單詞


' 正則模式
\b([a-z]+) \1\b
' 解析:
' \b      單詞邊界
' ([a-z]+) 捕獲群組1:一或多個字母
' \1      反向引用群組1 (相同單詞)
' \b      單詞邊界
' 旗標:g (全域) i (忽略大小寫) m (多行)

VBScript 代碼:


Dim ss, re, rv
ss = "Is is the cost of of gasoline going up up?" & vbNewLine
Set re = New RegExp
re.Pattern = "\b([a-z]+) \1\b"
re.Global = True
re.IgnoreCase = True
re.MultiLine = True
rv = re.Replace(ss, "$1")  ' 用第一個捕獲替換整個匹配
' 結果: "Is the cost of gasoline going up?"

實戰 2:解析 URI 元件


' 模式
(\w+)://([^/:]+)(:\d*)?([^# ]*)
' 群組1: 協議 (http, ftp...)
' 群組2: 域名 (不含 : /)
' 群組3: 埠號 (含冒號,可選)
' 群組4: 路徑/頁面 (不含 # 空格)

套用 https://msdn.microsoft.com:80/scripting/default.htm:

  • $1 = "http"
  • $2 = "msdn.microsoft.com"
  • $3 = ":80"
  • $4 = "/scripting/default.htm"

VBScript 完整代碼


Dim re, uri, matches
uri = "https://msdn.microsoft.com:80/scripting/default.htm"
Set re = New RegExp
re.Pattern = "(\w+)://([^/:]+)(:\d*)?([^# ]*)"
Set matches = re.Execute(uri)
If matches.Count > 0 Then
    For Each m In matches
        WScript.Echo "Protocol: " & m.SubMatches(0)
        WScript.Echo "Domain:   " & m.SubMatches(1)
        WScript.Echo "Port:     " & m.SubMatches(2)
        WScript.Echo "Path:     " & m.SubMatches(3)
    Next
End If

關鍵差異:JS vs VBScript

特性JavaScriptVBScript
模式分隔符/pattern/flags字串 + RegExp 物件屬性
反向引用 (模式內)\1\1
反向引用 (替換字串)$1$1
全域旗標/gre.Global = True
忽略大小寫/ire.IgnoreCase = True
多行模式/mre.MultiLine = True
copyright © 萬盛學電腦網 all rights reserved