2010-04-06 53 views
1

我的網址是這樣的:正則表達式來從URL獲取文章ID

www.example.com/a-292-some-text-here // 292 
www.example.com/a-2-asdfss  // 2 
www.example.com/a-44-333  // 44 

我需要一個正則表達式來從URL得到292。

的ID將總是整數。

我使用C#。

+0

會不會有永遠是一個','在它的前面?你能舉出更多可能的URL的例子嗎? – 2010-04-06 21:07:34

回答

2

使用Regex.Match@"\d+"

string input = "www.example.com/a-292-some-text-here"; 
Match match = Regex.Match(input, @"\d+"); 
if (match.Success) 
{ 
    int id = int.Parse(match.Value); 
    // Use the id... 
} 
else 
{ 
    // Error! 
} 
+0

感謝...更新了一些更多的例子。 – Blankman 2010-04-06 21:10:34

+0

@Blankman:我相信我上面提供的代碼給你想要的東西爲您的每個實例輸入。 – 2010-04-07 05:29:49