Sinan AKYAZICI
Sinan AKYAZICI

Reputation: 3952

How to get id from String with using Regex

I want to get only number id from string. result : 123456

var text = "http://test/test.aspx?id=123456dfblablalab";

EDIT:

Sorry, Another number can be in the text. I want to get first number after id.

var text = "http://test/test.aspx?id=123456dfbl4564dsf";

Upvotes: 5

Views: 6012

Answers (3)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Use:

Regex.Match(text, @"id=(\d+)").Groups[1].Value;

Upvotes: 8

Joe
Joe

Reputation: 15802

Someone will give you a C# implementation, but it's along the lines of

/[\?\&]id\=([0-9]+)/

Which will match either &id=123456fkhkghkf or ?id=123456fjgjdfgj (so it'll get the value wherever it is in the URL) and capture the number as a match.

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 160852

It depends on the context - in this case it looks like you are parsing a Uri and a query string:

var text = "http://test/test.aspx?id=123456dfblablalab";
Uri tempUri = new Uri(text);
NameValueCollection query = HttpUtility.ParseQueryString(tempUri.Query);
int number = int.Parse(new string(query["id"].TakeWhile(char.IsNumber).ToArray()));

Upvotes: 3

Related Questions