1.例子:匹配分割URL
反向引用還可以將通用資源指示符 (URI) 分解為其組件。假定您想將下面的 URI 分解為協議(ftp、http 等等)、域地址和頁/路: http://www.runoob.com:80/html/html-tutorial.html
var str = "http://www.runoob.com:80/html/html-tutorial.html";
var patt1 = /(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/;
arr = str.match(patt1);
for (var i = 0; i < arr.length ; i++) {
document.write(arr[i]);
document.write("<br>"); }
說明:
第三行代碼 str.match(patt1) 返回一個數組,實例中的數組包含 5 個元素,索引 0 對應的是整個字符串
(\w+) :匹配 http 該子表達式匹配://的任何單詞。
([^/:]+):匹配 www.runoob.com 子表達式匹配非 : 和 / 之后的一個或多個字符
(:\d*)?:匹配:80 該子表達式匹配冒號后面的零個或多個數字。只能重復一次該子表達式。
([^# ]*):匹配/html/html-tutorial.html 該子表達式能匹配不包括 # 或空格字符的任何字符序列。
運行結果為:
http://www.runoob.com:80/html/html-tutorial.html
http
www.runoob.com
:80
/html/html-tutorial.html