[英]Regex - Extract digits from a url
我有這個網址:
http://example.com/things/stuff/532453?morethings&stuff=things&ver=1
我只需要中間的那個號碼。 我最近的是
(\\ d *)?\\?
但這包括問號。 基本上所有在?之前的數字? 一直到斜線,所以輸出是532453。
嘗試以下正則表達式(?!\\/)\\d+(?=\\?)
:
url = "http://example.com/things/stuff/532453?morethings&stuff=things"
url.match(/(?!\/)\d+(?=\?)/) # outputs 532453
此正則表達式將僅嘗試在/
和之前匹配任何系列的數字?
通過使用負/正前瞻而不返回/
或?
作為比賽的一部分。
開發人員工具內的快速測試:
# create a list of example urls to test against (only one should match regex)
urls = ["http://example.com/things/stuff/532453?morethings&stuff=things",
"http://example.com/things/stuff?morethings&stuff=things",
"http://example.com/things/stuff/123a?morethings&stuff=things"]
urls.forEach(function(value) {
console.log(value.match(/(?!\/)\d+(?=\?)/));
})
# returns the following:
["532453"]
null
null
嘗試這個 :
url = "http://example.com/things/stuff/532453?morethings&stuff=things"
number = url.match(/(\d+)\?/g)[0].slice(0,-1)
盡管該方法有些天真,但可以。 它用? 最后刪除?
從最后開始使用slice
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.