Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get id from String with using Regex

Tags:

c#

.net

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";
like image 896
sinanakyazici Avatar asked Feb 23 '12 14:02

sinanakyazici


People also ask

What does \f mean in regex?

\f stands for form feed, which is a special character used to instruct the printer to start a new page. [*\f]+ Then means any sequence entirely composed of * and form feed, arbitrarily long.

What does $1 do in regex?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What is IG in regex?

The g and i modifiers have these meanings: g = global, match all instances of the pattern in a string, not just one. i = case-insensitive (so, for example, /a/i will match the string "a" or "A" .


3 Answers

Use:

Regex.Match(text, @"id=(\d+)").Groups[1].Value;
like image 133
Kirill Polishchuk Avatar answered Oct 09 '22 08:10

Kirill Polishchuk


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()));
like image 41
BrokenGlass Avatar answered Oct 09 '22 08:10

BrokenGlass


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.

like image 33
Joe Avatar answered Oct 09 '22 07:10

Joe