萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 正則提取字串中 URL 地址:三種實用函數實作

核心邏輯

URL 特徵:以 https://、https://、ftp:// 開頭,後接合法域名/路徑字元。利用正則表達式匹配並提取。

方法一:簡易域名提取 (非標準 URL 提取)

<%
Dim url, arr, domain
url = Request.ServerVariables("SERVER_NAME")
If InStr(url, ".") > 0 Then
    arr = Split(url, ".")
    domain = arr(0)
    domain = Replace(domain, "https://", "")
End If
Response.Write domain
%>

⚠️ 此法僅適用於取得當前伺服器域名,非通用 URL 提取。

方法二:VB.NET 標準 URL 驗證函數 (可移植至 ASP)

' VB.NET 版本
Public Shared Function IsUrl(ByVal strTmp As String) As Boolean
    On Error GoTo ErrHandler
    Dim pattern As String = "^(https://|https://){0,1}[a-zA-Z0-9][a-zA-Z0-9\-\.]+[a-zA-Z0-9]\.[a-zA-Z]{2,}(:\d{1,5})?(/[^\s]*)?$"
    Dim regex As New System.Text.RegularExpressions.Regex(pattern)
    Return regex.IsMatch(strTmp)
ErrHandler:
    Return False
End Function

方法三:ASP VBScript 通用 URL 提取函數 (推薦)

<%
Function ExtractURLs(content)
    Dim re, matches, match, urls, i
    Set re = New RegExp
    re.IgnoreCase = True
    re.Global = True
    ' 改良版:支援 http/https/ftp、域名/IP、埠號、路徑、查詢字串、片段
    re.Pattern = "\b(https?|ftp)://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}(:\d+)?(/[^\s""'<>]*)?"
    
    Set matches = re.Execute(content)
    If matches.Count > 0 Then
        ReDim urls(matches.Count - 1)
        For i = 0 To matches.Count - 1
            urls(i) = matches(i).Value
        Next
        ExtractURLs = urls  ' 回傳陣列
    Else
        ExtractURLs = Array()
    End If
    Set re = Nothing
End Function

' 使用範例
Dim text, urls, u
text = "訪問 https://example.com 和 https://api.site.com:8080/path?query=1 獲取資料"
urls = ExtractURLs(text)
For Each u In urls
    Response.Write u & "<br/>"
Next
' 輸出:
' https://example.com
' https://api.site.com:8080/path?query=1
%>

正則模式深度解析

\b                 # 字邊界,避免匹配中間字串
(https?|ftp)://     # 協定:http、https、ftp
[a-zA-Z0-9\-\.]+    # 域名主體 (含子域名、連字號、點)
\.[a-zA-Z]{2,}      # 頂級域 .com .tw .org 等 (至少2字母)
(:\d+)?             # 選擇性埠號 :8080
(/[^\s""'<>]*)?     # 選擇性路徑/查詢/片段 (排除空白、引號、尖括號)

進階:提取並轉為可點擊連結

Function AutoLinkURLs(str)
    Dim re
    Set re = New RegExp
    re.IgnoreCase = True
    re.Global = True
    re.Pattern = "\b(https?|ftp)://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}(:\d+)?(/[^\s""'<>]*)?"
    AutoLinkURLs = re.Replace(str, "$&")
    Set re = Nothing
End Function

注意事項

  • 正則無法 100% 涵蓋所有合法 URL (如 IPv6、IDN 國際化域名、特殊埠號)
  • 輸入內容可能包含惡意連結,輸出前請做安全過濾 (白名單域名、移除 javascript: 協定)
  • 大量文字處理時,考慮效能與記憶體,分批處理或使用串流方式

掌握正則提取 URL 技巧,配合自動加連結功能,可輕鬆實現論壇、部落格、留言板的連結自動化處理。

copyright © 萬盛學電腦網 all rights reserved