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