簡體   English   中英

如何在javascript正則表達式中使用反向引用?

[英]How do you use backreferences in javascript regular expressions?

我試圖使用正則表達式進行查找和替換,並將第一個(並且僅在這種情況下)反向引用作為變量。

var RegexSearchString = "/((?:^(?:https?://|www\\d{0,3}[.])(?:.*?/)|(?:[a-z0-9.\\-]+[.][a-z]{2,4}/))(?:.*?/))/";
var test = "http://foo.bar.net/interestingbit/lots/of/other/stuff/here";
alert(test);
test.replace(umassURLRegexSearchString, "$1");
alert(test);

預期結果應該是帶有以下內容的警報: http : //foo.bar.net/interestingbit/lots/of/other/stuff/here

緊隨其后的警報是: http : //foo.bar.net/interestingbit/

這兩個警報都包含首次初始化的測試變量的值。 有什么想法在哪里分解?

你需要:

  1. 添加一個新的捕獲組以將路徑上的第一個文件夾與其余文件夾分開
  2. 將正則表達式中的結束括號移到新的捕獲組之前
  3. 將正則表達式的結果分配回測試
  4. 轉義正則表達式中的所有/字符

所有這些更改的代碼是:

var RegexSearchString = /^((?:(?:https?:\/\/|www\d{0,3}[.])(?:.*?\/)|(?:[a-z0-9.\-]+[.][a-z]{2,4}\/))(?:.*?\/))(?:.*?\/)*/;
var test = "http://foo.bar.net/interestingbit/lots/of/other/stuff/here/";
alert(test);
test = test.replace(RegexSearchString, "$1");
alert(test);

在這里查看: http : //jsfiddle.net/jheHR/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM