圓括號 (...) 捕獲的子匹配會存入暫存緩衝區,編號 1-99。在模式中用 \1、\2... 反向引用;在替換字串中用 $1、$2...。
' 正則模式
\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?"
' 模式
(\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"
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
| 特性 | JavaScript | VBScript |
|---|---|---|
| 模式分隔符 | /pattern/flags | 字串 + RegExp 物件屬性 |
| 反向引用 (模式內) | \1 | \1 |
| 反向引用 (替換字串) | $1 | $1 |
| 全域旗標 | /g | re.Global = True |
| 忽略大小寫 | /i | re.IgnoreCase = True |
| 多行模式 | /m | re.MultiLine = True |