js中使用Regex,全域匹配時如何取到匹配串?

來源:互聯網
上載者:User

這次的測試用的是一個網址,主要的目的是用js把一段需要的文字提取出來,如下:
需要從中尋找的字串為:http://localhost:3095/agency_web/help.aspx?finish=1&agencyId=20
現在想要從它裡面提取出 localhost  、agency、help
匹配正則表達是為:/([^/]\w*)[\.|_|:]
以下是完整的帶代碼:
   var currentURL = “http://localhost:3095/agency_web/help.aspx?finish=1&agencyId=20”;
   var regStr = new RegExp("/([^/]\\w*)[:|\.|/]", "gi");
   var matchArr = currentURL.match(regStr);
這時候得到的是 /localhost:、/agency_和  /help.   實際上我要取得的是包含在()裡面的串,在本例中就是:localhost  、agency、help
那怎麼從得到的  /localhost:、/agency_和  /help.  中再取到  localhost  、agency、help呢?
js裡面沒有像C#那樣得到一個match之後這個match還有group分組

我知道在C#裡面的話可以用group,如下:
Regex areareg = new Regex(@"area=([^&]*)");// 用來檢測地區
string Indexarea = areareg.Match(IndexSQL).Groups[1].ToString();
areareg.Match(IndexSQL) 得到的是 area=南寧
再用Match.Groups[1]  就可以得到  “南寧”這個字串了。

繼續:如果上面的Regex改成 var regStr = new RegExp("/([^/]\\w*)[:|\.|/]", "i");,也就是把全域匹配的g去掉,
在執行 var matchArr = currentURL.match(regStr);
那樣的話就得到一個匹配,用alert(matchArr)、就可以知道這個數組裡麵包含了兩個元素:matchArr[0] =  /localhost:  、 matchArr[0] =  localhost    這個正是我想要的結果
但是他的缺點就是只匹配第一個,不知道用全域去匹配的時候能不能實現這個了,研究中

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.